in reply to Re^2: How to use modules dynamically?
in thread How to use modules dynamically?

Not really hard to replicate. First off, in the current directory, I created both a Z.pm, and a Z directory with X.pm - both Z.pm and X.pm had a single line: "1;". This is to eliminate, as much as possible, any constant overhead.

Benchmark code:

use strict; use Benchmark qw(cmpthese); my $module1 = 'Z'; my $module2 = 'Z::X'; cmpthese( 0, { evalSTR1 => sub { eval "use $module1"; delete $INC{'Z.pm'} }, evalSTR2 => sub { eval "use $module2"; delete $INC{'Z/X.pm'}; }, req1 => sub { (my $pm = $module1) =~ s.::./.g; $pm .= '.pm'; eval { require $pm }; delete $INC{'Z.pm'} }, req2 => sub { (my $pm = $module2) =~ s.::./.g; $pm .= '.pm'; eval { require $pm }; delete $INC{'Z/X.pm'} }, } );
And the results:
Rate evalSTR2 evalSTR1 req2 req1 evalSTR2 2474/s -- -2% -40% -48% evalSTR1 2538/s 3% -- -39% -47% req2 4150/s 68% 64% -- -13% req1 4779/s 93% 88% 15% --
run #2:
Rate evalSTR1 evalSTR2 req2 req1 evalSTR1 2348/s -- -4% -41% -44% evalSTR2 2438/s 4% -- -39% -41% req2 3964/s 69% 63% -- -5% req1 4158/s 77% 71% 5% --
Seems like more than 20% now. That said, if you find any faults in my benchmark, please, by all means, correct me.

As an interesting side-note, if it's possible that you're repeating a module-load (use/require), here's a benchmark showing that (all I did to the above code is remove the delete's):

Rate evalSTR2 evalSTR1 req2 req1 evalSTR2 14504/s -- -0% -94% -97% evalSTR1 14516/s 0% -- -94% -97% req2 262449/s 1709% 1708% -- -38% req1 424285/s 2825% 2823% 62% --
In the case of a first load, my require is faster, and in the case of a second or later reload attempt, my require is almost free, whereas recompiling your eval string is quite expensive, relatively speaking.

The big question is ... is it worth the difference? If I were putting this in time-critical (or possibly time-critical) code, probably. I don't think it's inherently obfu, so it's still pretty clean code. If I were putting this in code that can take its time, I might not waste the effort. Up to you to decide!