If you repeat that a few times you will see that in about 50 % of the
cases the procedural call is slightly faster than the oo call and in
50 % of the cases the oo call is slightly faster - or in other words,
the difference is not even measurable with a simple benchmark.
Totally agree but this particular code gives OO an
edge due to method caching.
A slight tweak: $arg . ("a".."z")[int(rand(26))]
consistently tilts for the faster procedural call ...
at least for some small Solaris and Linux sample
runs.
Interesting. I hadn't expected that the values of the arguments have an
influence on the method cache. How does the method cache work?
Actually, I just assumed that expensive method pointer
lookups were being cached and that leveled the playing
field. Normally, that extra lookup would slow the OO
call and procedural would win.
Well, the purpose of my test code was to find out how expensive these
pointer lookups really are. A single pointer lookup would be completely
insignificant compared to a normal perl subroutine call (which is
already quite expensive). A hash lookup would be more expensive. If @ISA
had to be searched (recursively) for each call, it would be even more
expensive. My simple benchmark indicated that the overhead was very low
(about 15ns per call), so I assumed it was only an extra pointer lookup
or so. Your modification dramatically increased the overhead of the oo
code (to about 285 ns per call). So my assumption was obviously wrong.
What irritates me is that I don't see what could cause the difference.
Also, I assume that if the method argument is constant, as it is
here, the call result itself could be cached too
No, this is not possible. Consider the call «rand(26)» in your code
(rand is a builtin, but it could easily be implemented in Perl): The
argument is a constant (26), but the return value changes every time.
If perl would cache the return value the result wouldn't be very random,
would it?
and that'd apply to the procedural call too.
Right.
In both the oo and the procedural case the compiler could determine that
a function is "pure" (i.e., the result depends only on the arguments)
and optimize accordingly. Perl doesn't afaik, with one important
exception: A function with prototype () returning a constant is inlined.
There is a module "Memoize" to add a caching layer to any sub.
hp