Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Does Perl do constant anonymous hash creation optimisation?

by Thilosophy (Curate)
on Jul 08, 2006 at 09:15 UTC ( #559913=note: print w/replies, xml ) Need Help??

in reply to Does Perl do constant anonymous hash creation optimisation?

The following (flawed, see below) experiment (prints out the memory location of the static hash) seems to suggest that Perl indeed creates the hash only once:
#!/usr/bin/perl sub static_hash { print { one => 1, two => 2 }; print $/; } static_hash; static_hash; static_hash;
planz$ perl /tmp/ HASH(0x1801380) HASH(0x1801380) HASH(0x1801380)
Update: Okay, forget about that, this just shows that a hash gets created in the same memory location. It could still be a new hash every time. In fact, changing the experiment to use a fresh hash yields exactly the same output:
#!/usr/bin/perl sub static_hash { print { one => $_[0], two => time }; print $/; } static_hash(8); static_hash(9); static_hash(10);

Replies are listed 'Best First'.
Re^2: Does Perl do constant anonymous hash creation optimisation?
by Anonymous Monk on Apr 27, 2009 at 22:45 UTC
    It definitely does -not- get optimized.
    perl -e 'my %bz = (x => 2, y=> 3, z=>4); sub baz { my $x = \%bz }; sub foo { my $x = { x => 1, y => 2, z=>3 } } sub bar { my $x = {x=>shift, y=>shift, z=>shift} } use Benchmark; timethese(-1,{foo=>\&foo,bar=>\&bar,baz=>\&baz});'
    Benchmark: running bar, baz, foo for at least 1 CPU seconds...
           bar:  2 wallclock secs ( 1.03 usr +  0.00 sys =  1.03 CPU) @ 607349.51/s (n=625570)
           baz:  1 wallclock secs ( 1.07 usr + -0.01 sys =  1.06 CPU) @ 3462279.25/s (n=3670016)
           foo:  2 wallclock secs ( 1.06 usr +  0.00 sys =  1.06 CPU) @ 618264.15/s (n=655360)
    Note the decimal point.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://559913]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (8)
As of 2016-09-25 17:25 GMT
Find Nodes?
    Voting Booth?
    Extraterrestrials haven't visited the Earth yet because:

    Results (470 votes). Check out past polls.