空文字列比較は eq/ne と length のどっちが速いか
最近、空文字列のチェックの際に、面倒臭くて $_ eq '' の代わりに、空文字列だと length が偽を返すことを利用して、自分しか見ないようなソースでは以下のように書くことが多いのですが、
return unless defined and length;
パフォーマンス的には、$_ ne '' と比べてどうなんだろうと思って調べてみました。
#!/usr/bin/perl use strict; use warnings; use Benchmark ':all'; my $empty = ''; my $not_empty = 'blah'; cmpthese(timethese(100000000, { emp_cmp_eq => sub { $empty eq '' }, emp_cmp_ne => sub { $empty ne '' }, emp_len => sub { length $empty }, not_cmp_eq => sub { $not_empty eq '' }, not_cmp_ne => sub { $not_empty ne '' }, not_len => sub { length $not_empty }, }));
結果は以下です。環境は Ubuntu 9.04 の v5.10.0 です。
Benchmark: timing 100000000 iterations of emp_cmp_eq, emp_cmp_ne, emp_len, not_cmp_eq, not_cmp_ne, not_len... Rate emp_cmp_eq emp_cmp_ne not_cmp_ne not_cmp_eq emp_len not_len emp_cmp_eq 11976048/s -- -11% -21% -37% -49% -64% emp_cmp_ne 13422819/s 12% -- -12% -29% -42% -59% not_cmp_ne 15220700/s 27% 13% -- -20% -35% -54% not_cmp_eq 18975332/s 58% 41% 25% -- -18% -42% emp_len 23255814/s 94% 73% 53% 23% -- -29% not_len 32894737/s 175% 145% 116% 73% 41% --
length の方が速いだろうとは思っていましたが、ここまで差が出たのが予想外でした。以後も積極的に length でチェックしようと思います。