http://www.perlmonks.org?node_id=37048

I was doing some coding today when I came to a spot where I needed to use an infinite loop. I remember reading about infinite loops in Programming Perl and that the "for" loop is most customary to use in such a situation. Being the skeptical person that I am, I thought, "It may be customary, but how does it Bench!" So I went and I Benchmarked three infinite loops which I had thought of at the time with this code:
#!/usr/bin/perl -w use strict; use Benchmark; timethese([X], { 'while' => sub { $_ = 0; while (1) { $_++; last if ($_ == 1000); + } }, 'for' => sub { $_ = 0; for (;;) { $_++; last if ($_ == 1000); + } }, 'block' => sub { $_ = 0; { $_++; redo if ($_ < 1000); + } } });

And after running this code with several different iterations (being the scientific person that I am), I came up with the following results:

Benchmark: timing 10000 iterations of block, for, while... block: 8 wallclock secs ( 8.13 usr + 0.00 sys = 8.13 CPU) for: 8 wallclock secs ( 7.90 usr + 0.00 sys = 7.90 CPU) while: 8 wallclock secs ( 8.03 usr + 0.00 sys = 8.03 CPU) Benchmark: timing 20000 iterations of block, for, while... block: 16 wallclock secs (16.25 usr + 0.00 sys = 16.25 CPU) for: 16 wallclock secs (15.80 usr + 0.00 sys = 15.80 CPU) while: 16 wallclock secs (16.08 usr + 0.00 sys = 16.08 CPU) Benchmark: timing 30000 iterations of block, for, while... block: 24 wallclock secs (24.37 usr + 0.00 sys = 24.37 CPU) for: 24 wallclock secs (23.69 usr + 0.00 sys = 23.69 CPU) while: 24 wallclock secs (24.08 usr + 0.00 sys = 24.08 CPU) Benchmark: timing 80000 iterations of block, for, while... block: 66 wallclock secs (65.01 usr + 0.00 sys = 65.01 CPU) for: 63 wallclock secs (63.18 usr + 0.00 sys = 63.18 CPU) while: 64 wallclock secs (64.20 usr + 0.00 sys = 64.20 CPU)

And once again, Programming Perl was absolutely right. The "for" loop was not only the customary infinite loop to use, but also the most efficient infinite loop to use. So now, I have been converted from while (1) { ... } to for (;;) { ... } and hopefully others will soon be converted, too.

Zenon Zabinski | zdog | zdog7@hotmail.com

Update: indigo pointed me in the direction of while() down the thread, and as you can see below, I found that while() was indeed faster than for(;;). Soo....