Watcom C/C++
  Contact Us

Extending a hash

Back to Perl Examples
The question came up on EFnet #perl as to how to 'push' one hash onto another.

The questioner asked if the following would do the trick:

    %hash = ( %hash, %morehash);
The channels immediate reaction was that this would be very slow. I wrote a one-liner benchmark:

bash$ perl -MBenchmark -e '@h{"aaa".."zzz"} = "AAA".."ZZZ"; 
> @m{"aa".."zz"} = "AA".."ZZ"; 
> timethese(-5, 
> { list=>q/%h = (%h, %m)/, 
> slice=>q/@h{keys %m} = values %m/})'
Benchmark: running list, slice, each for at least 5 CPU seconds...
      list:  6 wallclock secs ( 6.36 usr +  0.00 sys =  6.36 CPU) @  4.40/s (n=28)
     slice:  5 wallclock secs ( 4.99 usr +  0.01 sys =  5.00 CPU) @ 230.60/s (n=1153)

The slice is at least 50 times faster. Realize that the speed depends on the size of the destination and source hashes, but typically the slice is still faster.