[Wellington-pm] comparison and assignment: insignificant optimisation

Douglas Bagnall douglas at halo.gen.nz
Mon Jun 16 15:49:18 PDT 2014


On 16/06/14 23:09, Olly Betts wrote:
> A Perl scalar holding a string knows the string's length (it doesn't do
> something like calling C's strlen() function each time - it can't as the
> string might contain zero bytes) so length($foo) just loads a value from
> a field in a C structure to get the length.  It may need to turn the
> scalar into a string first, but if you call it more than once, only
> the first call should need to do that.

This is also how it works Python, but there the temporary variable
would probably[1] still be quicker than a double function call, due to
the way name resolution works. At compile time Python knows there is a
call to a something called len, but it doesn't know whether that
something is in local scope, a containing scope, the module global
scope, or built in to the interpreter. There are any number of ways
something can unexpectedly turn up in one of these namespaces, so the
interpreter has to look it up every time -- in exactly the wrong order
for finding the builtin len(). Which means that instantaneously
accessible length in the C struct is protected by about 4 hash
look-ups, while the local variable would be found in one hash look-up.

But Perl is different, right? Functions have their own scope hierarchy
and all that, so can the compiler know you mean the built-in length? I
am afraid I can't tell from Kent's disassembly.

cheers,

Douglas

[1] In the spirit of this thread, I offer no empirical results.
Besides which, we are optimising for Richard Hector non-irritation,
and I have no local copy.


More information about the Wellington-pm mailing list