3

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?

Sadko
  • 166
  • 9

3 Answers3

7

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?

cjm
  • 61,471
  • 9
  • 126
  • 175
  • I added the comments only here, in the example. – Sadko Jul 26 '12 at 03:36
  • @Sadko, I suspected as much, which is why my example didn't have a comment. The `// undef` may be clear to you, but I doubt it will be to anyone else reading your code. The comments, on the other hand, should be clear to anyone. – cjm Jul 26 '12 at 03:38
  • True. I was thinking about a reminder for myself. For other readers a comment is clearer. – Sadko Jul 26 '12 at 03:44
1

To answer your questions: Not and no.

ysth
  • 96,171
  • 6
  • 121
  • 214
0

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.

Sadko
  • 166
  • 9