in reply to does perl have branch prediction
There is a consistent but marginal difference when summing an unsorted array compared to summing the same array once sorted:
@a = map int( rand 256 ), 1 .. 10e6;; $t=time; $n=0; $_ > 128 and $n+=$_ for @a; print time-$t, " $n";; 1.42373704910278 952115465 @a = sort{ $a <=> $b } @a;; $t=time; $n=0; $_ > 128 and $n+=$_ for @a; print time-$t, " $n";; 1.31046295166016 952115465
However, the saving is not sufficient to make it worth while the very high cost of doing the sort:
@a = map int( rand 256 ), 1 .. 10e6;; $t=time; $n=0; $_ > 128 and $n+=$_ for @a; print time-$t, " $n";; 1.36710000038147 952320992 $t=time; @a = sort{ $a <=> $b } @a; $n=0; $_ > 128 and $n+=$_ for @a; +print time-$t, " $n";; 5.25063991546631 952320992
Perl doesn't attempt to optimise that complex conditional beyond short-circuiting early.
I'd be very surprised if pre-compiled C++ would reorder the clauses unless it is very obvious at compile-time that fun_Z() will predominantly produce a false return. It certainly won't reorder them at runtime, and unless all the functions in the conditional are very simple and in-lined, it is doubtful whether the branch-prediction at the chip-level will have sufficient scope to do so.
Java might re-order the clauses at runtime via the JIT compiler, if the complex conditional were embedded in a loop.
But, it would do so once during the first iteration of the loop and if during that pass fun_Z() returned its atypical response -- ie. if it returned false when it mostly would return true -- then it could result in an overall pessimisation rather than an optimisation, by seeding the branch prediction the wrong way.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: does perl have branch prediction
by david2008 (Scribe) on Jan 29, 2014 at 06:44 UTC | |
by BrowserUk (Patriarch) on Jan 29, 2014 at 07:06 UTC | |
by SimonPratt (Friar) on Jan 29, 2014 at 11:12 UTC | |
by roboticus (Chancellor) on Jan 29, 2014 at 11:53 UTC |