
A question of Style, was: SPUG: Sort an array question
Quote:
> > my personal preference would be to go with the 3-part for
> > since it's such a well-known idiom.
> More readable for the C folks, but about 60% slower than using the
> .. loop syntax.
> http://www.*-*-*.com/
Finding it hard to (intuitively) believe, and not being able to access
your site, I played around with Benchmark myself. Since I'm a C
programmer, my habits tend toward the familiar. I'm finding more and
more that folks don't have a C background. And more and more, I'm
finding that that's not just OK, it's good.
I'll share the code below.
I did find that C-style loops are slower than csh-style loops. In
order to take the list generation out of the loop, I created an array
of indices for the csh-style loop. As expected, it increased the
throughput. Likewise, I pre-calculated the upper bounds for the
C-style loop. It, likewise, increased the throughput, about cutting
the difference between a raw C-style and a csh-style loop. And just
for kicks, I proved what I already (intuitively) knew -- that getting
the element directly (without using the index) is still the fastest
way.
Thanks for pointing me to this new piece of knowledge.
Here's my benchmark code:
================================================================
#! /usr/bin/perl -w
use Benchmark qw(timethese cmpthese);
$i = 0; # Global. Don't time 'my' autovivication.
$code_hashref = {
"csh-ish" => sub { foreach $i (0 .. $#a) { $a[$i] = 0; } },
"C cheat" => sub { for ($i = 0; $i < a_len; $i++) { $a[$i] = 0; } },
Quote:
};
$results = timethese(0, $code_hashref);
cmpthese($results);
================================================================
And its output:
================================================================
Benchmark: running C cheat, C-ish, csh direct, csh nogen, csh-ish, each for at least 3 CPU seconds...
Rate C-ish C cheat csh nogen csh-ish csh direct
C-ish 58.6/s -- -20% -32% -40% -55%
C cheat 73.0/s 25% -- -15% -25% -44%
csh nogen 86.4/s 47% 18% -- -11% -34%
csh-ish 97.4/s 66% 33% 13% -- -26%
csh direct 131/s 124% 80% 52% 35% --
================================================================
--
Michael R. Wolf
All mammals learn by playing!