Initialising with “undef” for self-documenting code?
Domanda
Sometimes I'd like to write:
my $var = shift // undef; # argument is optional
# or
my $var = $val{optional_value} // undef;
to indicate that it is ok to have the argument missing, otherwise // undef
is useless, of course.
How expensive is this, is it optimized away by the compiler?
Soluzione
To answer your questions: Not and no.
Altri suggerimenti
I'm sure it's not very expensive, but I have to say that
my $var = shift // undef;
is not nearly as clear as
my $var = shift; # argument is optional
or
my $var = shift; # optional; undef if omitted
Which are both definitely (although barely) cheaper at runtime. If you need the comment anyway (for clarity), then what does // undef
really add except unnecessary opcodes?
I tried a benchmark:
use strict;
use Benchmark qw(:all);
sub shu
{
my $x = shift // undef;
return $x // 0;
}
sub sh
{
my $x = shift;
return $x // 0;
}
timethese ( 100_000_000, { shu => \&shu, sh => \&sh } );
# outputs:
# Benchmark: timing 100000000 iterations of sh, shu...
# sh: 14 wallclock secs (14.95 usr + -0.06 sys = 14.89 CPU) @ 6715916.72/s (n=100000000)
# shu: 16 wallclock secs (16.74 usr + -0.02 sys = 16.72 CPU) @ 5980861.24/s (n=100000000)
So the results confirm what was said above.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow