36
$\begingroup$

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:

Thank you for your message.

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]

$\endgroup$
2
  • $\begingroup$ Neither of them seem to unpack the array. Maybe this is something that should be reported to support. $\endgroup$
    – Szabolcs
    Nov 25, 2013 at 19:01
  • $\begingroup$ Results are the opposite for SparseArray objects $\endgroup$ Nov 25, 2013 at 20:38

1 Answer 1

11
$\begingroup$

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 = Developer`FromPackedArray @ mat;

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.