7
$\begingroup$

Answered in comments.

I find the built-in function IntegerReverse[n] is roughly an order of magnitude slower than the simple alternative FromDigits[Reverse[IntegerDigits[n]]].

Tests were made with the following code:

testnumbers = Range[10^4];
(IntegerReverse /@ testnumbers;) // Timing
((FromDigits[Reverse[IntegerDigits[#]]]&) /@ testnumbers;) // Timing

Version 11 gives:

{0.140625, Null}
{0.015625, Null}

Version 10 (on a different machine) gives:

{0.0625, Null}
{0.015625, Null}

This is a huge difference. I'm wondering if I'm missing a slowing feature of IntegerReverse or something like that.

Can anyone confirm this result? Should we report this to wolfram?

$\endgroup$
  • 1
    $\begingroup$ You may be interested in evaluating <<GeneralUtilities`; PrintDefinitions[IntegerReverse] to see the features and spot the differences. $\endgroup$ – user31159 Sep 15 '16 at 12:06
  • $\begingroup$ Thanks. This answers the question. I did not thought, that this small overhead produces such a delay in evaluation. $\endgroup$ – Julien Kluge Sep 15 '16 at 12:14
10
$\begingroup$

A substantial part of the timing difference in this example is due to the automatic compilation used by Map. Note the crossover setting

SystemOptions["CompileOptions" -> "MapCompileLength"]

(* {"CompileOptions" -> {"MapCompileLength" -> 100}} *)

and compare

testnumbers = Range[10^4];
AbsoluteTiming[Map[FromDigits[Reverse[IntegerDigits[#]]] &, testnumbers];]

(* {0.006648, Null} *)

with

SetSystemOptions["CompileOptions" -> "MapCompileLength" -> Infinity];   
AbsoluteTiming[Map[FromDigits[Reverse[IntegerDigits[#]]] &, testnumbers];]

(* {0.015754, Null} *)

The relevant part of the implementation of IntegerReverse, while straightforward and seemingly similar

Attributes[IntegerReverse] := {Listable, Protected, ReadProtected};
IntegerReverse[n_Integer] := With[{digits = Quiet @ IntegerDigits @ n},
     FromDigits[Reverse[digits]] /; ListQ[digits]];

is not compilation-friendly. This weakness may be addressed by a future version of the compiler.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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