[Chicago-talk] Which "if" structure is faster?

Jim Thomason jthomasoniii at yahoo.com
Sat Feb 21 12:41:39 CST 2004


This actually caught my attention and I figured I'd
give it a crack. I was quite surprised with the
results.

use Benchmark;

timethese(500000, {
  'if' => sub {
    my $x = 5;
    if ($x - 5 != 0) {
      foreach my $idx (1..100) {
        my $foo = $idx ** 2;
        $foo -= 17;
      }
    } else {
      #who cares?
    }
  },
  'else' => sub {
    my $x = 5;
    if ($x - 5 == 0) {
      #who cares?
    } else {
      foreach my $idx (1..100) {
        my $foo = $idx ** 2;
        $foo -= 17;
      }
    }
  }
});

Benchmark: timing 500000 iterations of else, if...
  else:  2 wallclock secs ( 0.70 usr +  0.10 sys = 
0.80 CPU) @ 625000.00/s (n=500000)
  if:  7 wallclock secs ( 1.96 usr +  0.00 sys =  1.96
CPU) @ 255102.04/s (n=500000)

Naturally, I have no clue what your code is like, so I
just inserted a time waster.

As you can see, the else clobbers the if, running
slightly more than twice as fast. I would've expected
the if to be slightly faster, just assuming that the
'else' would have to jump in the code but the 'if'
would have the code in place (I have no basis for that
assumption, just seemed logical to me). Not knowing
squat about the perl internals, I can't even
hypothesize as to why the else is so much faster.
Perhaps my test was flawed in some manner I'm not
seeing.

Regardless, also note that the difference is
255,000/sec vs. 625,000/sec. Realistically, I'd say
this "optimization" will be utterly completely totally
negligible. If you're trying to squeeze out
performance, look elsewhere. 

Result? Write whichever one looks more clear in the
code. Maintainability would be the issue here, not
speed. Also, you might want to consider moving the
"first time" check out of the loop and doing it in
advance. If that's your only special case, you could
step through it and do it, and then begin your
infinite loop w/o the special case. Assuming your code
would allow you to break it out of the loop, of
course.

-Jim.....

--- Jay Strauss <me at heyjay.com> wrote:
> Hi,
> 
> If I have some one time processing, then a endless
> loop (till the proc is
> killed).  Which is faster or are they the same:
> 
> if ($firstTime) {
>     ...stuff...
>     $firstTime = 0;
> }
> else {
>     ...stuff...
> }
> 
> 
> or
> 
> 
> if (! $firstTime) {
>     ...stuff...
> }
> else {
>     ...stuff...
>     $firstTime = 0;
> }
> 
> 
> Just curious
> Jay
> 
> _______________________________________________
> Chicago-talk mailing list
> Chicago-talk at mail.pm.org
> http://mail.pm.org/mailman/listinfo/chicago-talk


__________________________________
Do you Yahoo!?
Yahoo! Mail SpamGuard - Read only the mail you want.
http://antispam.yahoo.com/tools



More information about the Chicago-talk mailing list