in reply to does perl have branch prediction
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
|
|---|