# Why is multidimensional Reverse slow?

Bug introduced in 6.0 or earlier and persisting through 11.1.1 or later

I have found that multidimensional Reverse is ~10 times slower than exact -1 ;; 1 ;; -1:

n = 1000;
mat = RandomReal[1, {n, n}];

mat2 = Reverse[mat, 2]; // AbsoluteTiming
mat3 = mat[[All, -1 ;; 1 ;; -1]]; // AbsoluteTiming
(* {0.088234, Null} *)
(* {0.006836, Null} *)

mat2 == mat3
(* True *)


Why? Is it a bug?

Both produced arrays are packed.

I use Mathematica 9.0.1 on Linux. Mathematica 8 has the same problem.

Reply from the Wolfram Technical Support:

I could reproduce this performance issue on Mathematica 9.

I have filed a report on this to our database and thank you for bringing this issue to our attention.

Wolfram Technical Support case identification : [CASE:424077]

• Neither of them seem to unpack the array. Maybe this is something that should be reported to support. – Szabolcs Nov 25 '13 at 19:01
• Results are the opposite for SparseArray objects – Dr. belisarius Nov 25 '13 at 20:38

Mathematica is full of these idiosyncrasies and honestly I have no idea how one is to figure out why. Still I think it's an interesting question. One possibility is that Part was optimized at some point and Reverse got left behind. In my experience Part is highly optimized for packed arrays. At least in v7 Reverse is faster on unpacked data:

SetAttributes[timeAvg, HoldFirst]

timeAvg[func_] :=
Do[If[# > 0.3, Return[#/5^i]] & @@ Timing@Do[func, {5^i}], {i, 0, 15}]

mat = DeveloperFromPackedArray @ mat;

Reverse[mat, 2];           // timeAvg
mat[[All, -1 ;; 1 ;; -1]]; // timeAvg

0.005872

0.009736

• In 10.3 the difference is quite small (2%), but it exits. – ybeltukov Nov 7 '15 at 13:44
• The difference is small only for unpacked arrays as in your answer. For packed arrays Reverse` is still 10 times slower. – ybeltukov Nov 9 '15 at 2:27