i'd like to know what exactly happens when i use reflection to call a method whose name i have as a string:
my $foo = Foo->new();
my $method = 'myMethod';
$foo->$method();
is ~20% slower than native call:
$foo->myMethod();
Any pointers to documentation about how perl's reflection is implemented would be helpful.
Thanks.
> perl -MO=Concise -e '$foo->$bar'
8 <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 1 -e:1) v:{ ->3
7 <1> entersub[t3] vKS/TARG ->8
3 <0> pushmark s ->4
- <1> ex-rv2sv sKM/1 ->5
4 <#> gvsv[*foo] s ->5
6 <1> method K/1 ->7 # ops to read $bar and then call method
- <1> ex-rv2sv sK/1 ->6 #
5 <#> gvsv[*bar] s ->6 #
-e syntax OK
> perl -MO=Concise -e '$foo->bar'
7 <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 1 -e:1) v:{ ->3
6 <1> entersub[t2] vKS/TARG ->7
3 <0> pushmark s ->4
- <1> ex-rv2sv sKM/1 ->5
4 <#> gvsv[*foo] s ->5
5 <$> method_named[PV "bar"] ->6 # op to call the 'bar' method
-e syntax OK
In the first example, perl has to load the $bar
variable, and then check to see if it contains a name or value that can be used as a method. Since the contents of $bar
could change between calls, this lookup must be done each time.
In the second example, perl already knows that the string "bar"
should be used as a method name, so this avoids loading the variable and checking its contents on each execution.
But you should not worry too much about a 20% percent speed difference between two native operations. Mainly because native operations are very fast, and any speed that they actually do require will quickly be dwarfed by the actual algorithm your code has to perform. In other words, unless you have isolated this issue as a hot spot with a code profiler, the speed difference has more pedagogical than practical importance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With