nil

TorgoX on 2002-04-09T09:51:50

Dear Log:

A thing I do a lot:

use constant nil => [];

...
foreach my $x (@{ $thing || nil }) {
  ...

Ideally it's reusing the same arrayref every time, whereas if I did "@{ $thing || [] }" it'd be making a new empty arrayref every time $thing is false, just to immediately throw it away. To wit:

use strict;
use constant nil => [];
use Benchmark;
my $y;
timethese(10000000,
{
way1 => sub {foreach my $x (@{$y || nil}) { print ''; } return },
way2 => sub {foreach my $x (@{$y || []}) { print ''; } return },
});

__END__
Benchmark: timing 10000000 iterations of way1, way2...
way1: 22 wallclock secs (21.25 usr + 0.00 sys = 21.25 CPU) @ 470588.24/s (n=10000000)
way2: 47 wallclock secs (46.30 usr + 0.00 sys = 46.30 CPU) @ 215982.72/s (n=10000000)

So, a whopping ~3 MICROsecond difference -- compared to something probably astronomically greater just to load constant.pm and call its import(). Ahwell, I can dream, can't I? And what if I think "|| nil" just looks better? IS THAT SO WRONG?


putting the 'I' in 'Rationalizations'

jjohn on 2002-04-09T12:58:28

TorgoX, you slay me.