G'day david2008,

"I came over an interesting post in stackoverflow It explains that in Java/C++ processing a sorted array is faster than an unsorted."

Firstly, it reports an observation; it doesn't "explain" a fact. Secondly, if you read further, you'll find the OP writes things like "I did investigate a bit further, and things are "funny"." and "... so it really has nothing to do with the data being sorted, ...".

Use Benchmark to compare the running times of Perl code.

What you can do in Perl is this:

#!/usr/bin/env perl -l use strict; use warnings; my @a = (1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024); { print '*** Unsorted ***'; my ($sum, $iterations) = (0, 0); for my $x (@a) { if ($x > 128) { $sum += $x; } ++$iterations; } print "Sum: $sum"; print "Iterations: $iterations"; } { print '*** Sorted ***'; my ($sum, $iterations) = (0, 0); for my $x (sort { $b <=> $a } @a) { last unless $x > 128; $sum += $x; ++$iterations; } print "Sum: $sum"; print "Iterations: $iterations"; }

Output:

*** Unsorted *** Sum: 1792 Iterations: 11 *** Sorted *** Sum: 1792 Iterations: 3

To what degree the processing involved in sorting the data offsets any gains in a reduction of iterations will depend on the size of the array and the value of the elements (for instance, if all values are greater than 128, then sorting would be entirely wasteful and useless).

-- Ken


In reply to Re: does perl have branch prediction by kcott
in thread does perl have branch prediction by david2008

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.