That was cbraga's original solution and he abandoned it because keys builds the whole list prior to usage. each doesn't do that.
Being right, does not endow the right to be rude; politeness costs nothing. Being unknowing, is not the same as being stupid. Expressing a contrary opinion, whether to the individual or the group, is more often a sign of deeper thought than of cantankerous belligerence. Do not mistake your goals as the only goals; your opinion as the only opinion; your confidence as correctness. Saying you know better is not the same as explaining you know better.
I shouldn't have to say this, but any code, unless otherwise stated, is untested
| [reply] |
keys builds the whole list prior to usage
I thought I remember reading somewhere that keys has an optimization in this case, and the whole list is not actually built up front. I couldn't find any documentation, so I decided to do a few tests. Perhaps my test code is flawed in some way I don't see, but the results seem to agree with my premise.
Here are my snippets:
Here's a table with the results:
Update: I should have mentioned earlier, these are from perl 5.005_03 on FreeBSD 4.9-STABLE. I got the value from the VSZ column in ps aux output.
The change from snippet a to b is much larger than the change from a to c. This seems consistent with the optimization I thought should occur. There may be overhead in the array @keys, but I wouldn't think it would be so much more than building an equivalent list. Maybe someone can explain this another way?
| [reply] [d/l] [select] |
perl -le '%hash = (1 .. 1000000); for (keys %hash) { print ">"; <STDI
+N> ; exit}'
to ease the snippets death.I just used top to look at the Size column, and my results are
COUNT | a mem | b mem | c mem | a-b change | a-c change |
100,000 | 10,960 | 11,984 | 11,004 | 1,024 (9.3%) | 44 (0.4%) |
1,000,000 | 94,324 | 101,000 | 94,460 | 6,676 (7.1%) | 136 (0.1%) |
Note the top in RH9 truncates snippet B, 1,000,000 items to 101M, and I haven't figured out how to change the units for this field - perhaps I need to use something other than top...
So in conclusion, I agree, it does appear there is some optimisation going on - is this an example of lazy evaluation ?
| [reply] [d/l] |