![]() |
|
We don't bite newbies here... much | |
PerlMonks |
perl 5.36 and the for_list feature - a simple speed comparisonby swl (Vicar) |
on Jun 21, 2022 at 09:32 UTC ( #11144892=perlmeditation: print w/replies, xml ) | Need Help?? |
Perl 5.36 has a new feature that iterates over multiple values at a time in a for loop (perldelta entry here). Any number of values can be specified, but the pairwise case is the focus here. The for_list feature is a useful alternative to a while-each idiom over a hash when working with key-value pairs. It also allows one to natively work with arrays of key-value pairs without converting them to a hash (and thus losing values associated with duplicate keys). Speed is one factor in the decision to updated code, so I figured I would see how fast the new feature is compared with while-each and some other approaches using List::Util functions. Some benchmark code is below (inside readmore tags), with results following. Benchmark labels starting with a_ operate on array data while those with h_ operate on hash data. I note that it is fairly well documented that the while-each idiom is best avoided because the hash iterator has global state and thus can cause action at a distance. In the benchmark code the hash is only accessed this way in one sub. The summation of the hash values in the loops is merely something for the loop to do that would have relatively low overhead compared with the looping itself. The hash_vals sub is done as a point of comparison. There is no reason why one would iterate over both keys and values when only the values are needed. Code was run under Ubuntu 20.04 under WSL2 for Windows. The main conclusion is that the new feature is faster than all the others when an array is used. It is faster than all of the hash approaches that use both keys and values. Profiling shows the cause of the slowdown when using List::Util::pairs is the dereference of the pair array, which is not surprising. Using the declared_refs feature does not help in this case. Overall I quite like the new for_list feature. Aside from being faster than many of the alternatives, it is also much cleaner.
Results:
Back to
Meditations
|
|