|Keep It Simple, Stupid|
The High Price of Golf, and A Surpriseby Zaxo (Archbishop)
|on Sep 07, 2002 at 08:28 UTC||Need Help??|
It occured to me, in a fit of dementia, that a numeric sort with subtraction instead of the <=> operator would shave two strokes in Perl Golf. I became curious about the cost of doing that.
I threw together a benchmark and got a surprise.
No, the subtraction method isn't fast: in fact, it more than doubles the time taken in sorting. The surprise is that the spaceship operator is faster than dictionary sort.
Received wisdom in the Perl community is that its string sort is optimum and there is a price to pay for numeric sort. In this benchmark, each type of sort receives the same data, but already cast to float, integer, or string. As much extra processing as possible is outside the timing loop, so that only sort performance is measured, without any representation penalties for one method over another. Spaceship is not penalized by a string-to-float conversion, for instance. The numbers are the same, but each method gets them in predigested form. No measured time is spent on my or other allocation, since the result is stored in a preallocated array, sized to the data it will receive.
The data (Edit - New, from corrected code):
Each is a sort of 10000 random numbers from
It appears to me that spaceship's reputed slowness goes away when its data is already numeric, and the arena is levelled by insisting on equivalent data for both forms of sort.
Here is the benchmark code (Edit - Corrected to avoid negative range and to word align strings):
Update: Code and data corrections, thanks to bart for the spot.
Edit by tye to change PRE to CODE around wide lines