A question of Style, was: SPUG: Sort an array question 
Author Message
 A question of Style, was: SPUG: Sort an array question


> > 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

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; } },


$results = timethese(0, $code_hashref);

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!

Fri, 17 Jun 2005 12:39:02 GMT  
 [ 1 post ] 

 Relevant Pages 

1. Two questions

2. SQL Update Help Required

3. YAPSQ (Perl Style Question): sorting and maintaining sorted order

4. Sorting question: I think I am missing something obvious

5. sorting array of array question

6. Style question for class with hashs & arrays

7. Style question for class with hashs & arrays

8. Moving a pointer to the end of a record file

9. NL DevCon (CttM'96): Call for Speakers

10. Delphi vs Oracle 7.1

11. TNMSMTP - Component (Host)

12. Access >> Delphi


Powered by phpBB® Forum Software