有时候,我真想写:使用“undef”初始化自编码代码?
my $var = shift // undef; # argument is optional
# or
my $var = $val{optional_value} // undef;
,以表明它是确定有说法缺少,否则// undef
是没用的,当然。
这是多么昂贵,它由编译器优化了吗?
有时候,我真想写:使用“undef”初始化自编码代码?
my $var = shift // undef; # argument is optional
# or
my $var = $val{optional_value} // undef;
,以表明它是确定有说法缺少,否则// undef
是没用的,当然。
这是多么昂贵,它由编译器优化了吗?
要回答你的问题:不是。
我敢肯定,它不是很贵,但我不得不说,
my $var = shift // undef;
是几乎没有
my $var = shift; # argument is optional
或
my $var = shift; # optional; undef if omitted
这两者都是一样清晰在运行时绝对(尽管很少)便宜。如果您需要评论(为了清晰起见),那么除了不必要的操作码之外,// undef
还会添加什么内容?
我尝试了标杆:
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)
所以结果证实了上面说。
你可能想要找出一个基准。 – Jokester 2012-07-26 02:45:28
如果我在生产代码中看到这种情况,我很可能会认为这是一个错误。坚持评论,如果你觉得他们需要 – Borodin 2012-07-26 08:27:53