in reply to Efficient Looping Constructs

I think it should also be noted that loops in general are ineffecient. Not that you should avoid them, but under certian circumstances you can optimize your code by not using one. I was a little reluctant to post this because I don't want to misdirect people to think that they should be trying to optimize away their loops. So I'll say that under very limited circumstances, you might want to consider this. Those limited circumstances would be when you notice that you have a substancial bottleneck where you're looping over a static number of elements (known at compile time).

Here's an example..

#!/usr/bin/perl -w use strict; use Benchmark; timethese(100000, { 'loop' =>'loop()', 'noloop' => 'noloop()' }); sub loop { my $x; for (1..10) { $x++; } } sub noloop { my $x; $x++; $x++; $x++; $x++; $x++; $x++; $x++; $x++; $x++; $x++; }
Results:
Benchmark: timing 100000 iterations of loop, noloop... loop: 4 wallclock secs ( 3.48 usr + 0.03 sys = 3.51 CPU) @ 28 +490.03/s ( n=100000) noloop: 0 wallclock secs ( 1.09 usr + 0.00 sys = 1.09 CPU) @ 91 +743.12/s ( n=100000)
Now in this example, the for loop works just fine, but as you can see, not using a loop is three times as fast. %99.9 of the time, you're not going to have to optimize this unless you're calling this 100k times.

Anyway, I just thought I'd throw it out there..

Rich