Hola monks!

I wrote the following snippet to compare various basic sorts:

use strict; use warnings; use Benchmark 'cmpthese'; srand 0; my @n = map int(rand(2**7)), 1..1000; my @a = map chr($_), @n; cmpthese( -1, { default_n => sub { ( sort @n )[ 0 ] }, cmp_n => sub { ( sort { $a cmp $b } @n )[ 0 ] }, '<=>' => sub { ( sort { $a <=> $b } @n )[ 0 ] }, default_a => sub { ( sort @a )[ 0 ] }, cmp_a => sub { ( sort { $a cmp $b } @a )[ 0 ] }, } ); __END__ Rate cmp_n default_n cmp_a default_a <=> cmp_n 667/s -- -0% -3% -3% -40% default_n 667/s 0% -- -3% -3% -40% cmp_a 691/s 4% 4% -- 0% -38% default_a 691/s 4% 4% 0% -- -38% <=> 1110/s 66% 66% 61% 61% --

I'm having a hard time rationalizing why <=> did so much better than the default alphabetic sort, since it was my understanding that the latter should be better. I think the comparison above is fair; am I wrong?

BTW, I figure that the reason why default_n fares worse than default_a is that the former is comparing strings of length up to 3, while the latter is comparing strings of length 1.

the lowliest monk


In reply to Yet Another Sort Benchmarking Question by tlm

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.