in reply to
Re^3: Undefined vs empty string

in thread Undefined vs empty string

Speed very much depends on what is the most likely value to occur in the tests. `length` for sure is not always faster. I prefer using defined-or:

`$ cat test.pl
use 5.014;
use warnings;
use Benchmark qw(cmpthese);
foreach $a (undef, "", 0, 1, "x" x 60) {
say "Testing for a = ", $a // "undef";
cmpthese (-1, {
def_eq => sub { for (0..1000) { ! defined $a || $a eq "" ? 1 :
+0; }},
def_len => sub { for (0..1000) { !(defined $a && length $a) ? 1 :
+0; }},
dor_eq => sub { for (0..1000) { ($a // "") eq "" ? 1 :
+0; }},
});
}
$ perl test.pl
Testing for a = undef
Rate dor_eq def_eq def_len
dor_eq 9135/s -- -21% -21%
def_eq 11499/s 26% -- -1%
def_len 11605/s 27% 1% --
Testing for a =
Rate def_len def_eq dor_eq
def_len 7110/s -- -8% -25%
def_eq 7729/s 9% -- -19%
dor_eq 9489/s 33% 23% --
Testing for a = 0
Rate def_len def_eq dor_eq
def_len 7518/s -- -12% -29%
def_eq 8533/s 14% -- -19%
dor_eq 10577/s 41% 24% --
Testing for a = 1
Rate def_len def_eq dor_eq
def_len 7518/s -- -12% -29%
def_eq 8533/s 14% -- -19%
dor_eq 10577/s 41% 24% --
Testing for a = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+xxxxxx
Rate def_len def_eq dor_eq
def_len 7450/s -- -13% -30%
def_eq 8533/s 15% -- -20%
dor_eq 10676/s 43% 25% --
$
`

Enjoy, Have FUN! H.Merijn