Skip to content

Instantly share code, notes, and snippets.

@anazawa
Last active December 14, 2015 18:59
Show Gist options
  • Select an option

  • Save anazawa/5133404 to your computer and use it in GitHub Desktop.

Select an option

Save anazawa/5133404 to your computer and use it in GitHub Desktop.
CGI->can
use strict;
use warnings;
use Benchmark 'cmpthese';
use CGI;
package Cat;
sub walk {}
package main;
cmpthese(-1, {
'CGI->can("new")' => sub {
my $code = CGI->can('new'); # compiled by default
},
'CGI->can("cache")' => sub {
my $code = CGI->can('cache'); # autoloaded on demand
},
'CGI->can("no_cache")' => sub {
my $code = CGI->can('no_cache'); # doesn't exist
},
'Cat->can("walk")' => sub {
my $code = Cat->can('walk');
},
'Cat->can("run")' => sub {
my $code = Cat->can('run');
},
});
__END__
Rate CGI->can("no_cache") CGI->can("new") CGI->can("cache") Cat->can("walk") Cat->can("run")
CGI->can("no_cache") 6516/s -- -98% -98% -100% -100%
CGI->can("new") 267962/s 4012% -- -1% -79% -83%
CGI->can("cache") 270491/s 4051% 1% -- -79% -83%
Cat->can("walk") 1303975/s 19911% 387% 382% -- -20%
Cat->can("run") 1622942/s 24806% 506% 500% 24% --
  • CGI.pm overrides the UNIVERSAL->can method, and so CGI->can is basically slower than an ordinary module's. That's not so amazing.
  • Though CGI.pm implements the cache method, the method is not compiled by default, but autoloaded on demand.
  • CGI->can("no_cache") always returns false because the method is not implemented by CGI.pm.
  • According to the above benchmark result, CGI->can("no_cache") is much slower than CGI->can("cache"). That's the problem.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment