http://www.perlmonks.org?node_id=1015951


in reply to Speed up hash initialization loop

write $profEvntVar->{$customProf} only once, assign the ref to a lexical, then deref the lexical each time. You cut 2 lookups to 1 on each line.

Replies are listed 'Best First'.
Re^2: Speed up hash initialization loop
by roboticus (Chancellor) on Jan 30, 2013 at 13:46 UTC

    bulk88:

    So the compiler doesn't do a 'common subexpression elimiation' optimization? Or does it do such a thing, but it can't optimize that due to the possibility of too much "magic" going on?

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      Correct. $profEvntVar may be magical and return a different hash every time its read. In that hash, slice {$customProf} might be magical and different every time. If you write the var X many times in source, it will be called/read X many times in source. There is no caching.
      I'm not using a compiler... actually I didn't even know there where perl compilers, but if you point me in the right direction I'd be happy to learn
Re^2: Speed up hash initialization loop
by austinj (Acolyte) on Jan 30, 2013 at 14:34 UTC

    This sounds like what I need to do but I don't understand where to deref. Should this be within the subroutine? If it is outside of the subroutine, I think I'm already doing this, my %profEvntVar is defined above, and in the end I need it to contain all of the info about each profile in @profiles

    Sorry if I'm missing something

      if(exists $profEvntVar->{$customProf}){next;} my $cprof = $profEvntVar->{$customProf} = {}; my ($evnt_nums_ref,$var_names_ref,$variables_ref,$last_evn +t_name) = getvars($customProf); $cprof->{events} = $evnt_nums_ref; #Link profiles with th +eir respective events $cprof->{times} = $evnt_times_ref; #Link profiles with th +eir respective events # etc

      FWIW, I don't think there'll be much gain (it should be in the order of microseconds), but since they're in a loop it might add up. This is not really an optimisation technique, but a code cleanup one.

      (Do change the naming of $cprof if you can think of a better name.)