in reply to Re: is 'my' that much faster than 'local'?
in thread is 'my' that much faster than 'local'?

Using twerq's original script, I got similar results on an ActiveState Perl/Win32 machine: my was more than twice as fast as local.

However, I modified twerq's script so that each variable is only declared once. Here is the modified script, which measures time to access or change variables rather than to declare them:

# replace local with "my" local $start_time = time; local $global_variable = "hello!"; for (local $i = 0; $i < 5000000; $i++) { $global_variable = "redefined. . "; } print time - $start_time." seconds\n"; print "$global_variable\n";
The program now takes 24 seconds when local is used and 18 when my is used. So it appears that local can introduce significant overhead into a program even when the program only declares variables a few times but accesses them over and over.

Replies are listed 'Best First'.
Re: is 'my' that much faster than 'local'?
by Dominus (Parson) on Mar 27, 2001 at 21:32 UTC
    Says sierrathedog04:
    So it appears that local can introduce significant overhead into a program even when the program only declares variables a few times but accesses them over and over.
    Sure. Global variables must be looked up in the symbol table. This is essentially a hash lookup. Lexical variables are retrieved from the scratchpad, which is an array. Arrays are always going to beat hashes for speed.

    But I still think my main point is correct: It doesn't matter which one is faster, because they do different things. You use local when it is appropriate, and my when you need my, not because it is faster.

    Comparing them for speed doesn't make sense. What would you think if someone asked you whether open was faster or slower than getprotoent? You can write all the benchmarks you want to compare open with getprotoent, and none of them are going to mean a thing.