2009-01-20

Enumerate lists AND single items

So far when I wanted to make sure I have something to iterate over I used following snippet:


[variable].flatten

This is not accurate in case variable is an array of arrays but was enough for most of my cases.

Today I have found a nice trick on Ruby Inside:


[*variable]

Not only it's fully accurate, it also has speed advantage over previous solution (benchmark code):


Rehearsal ------------------------------------------------------------
Single element flatten     0.110000   0.000000   0.110000 (  0.118731)
Single element splat       0.190000   0.000000   0.190000 (  0.196618)
Multiple element flatten   6.800000   0.090000   6.890000 (  7.115833)
Multiple element splat     0.070000   0.000000   0.070000 (  0.076305)
--------------------------------------------------- total: 7.260000sec

                               user     system      total        real
Single element flatten     0.260000   0.000000   0.260000 (  0.270906)
Single element splat       0.320000   0.010000   0.330000 (  0.338638)
Multiple element flatten   6.450000   0.060000   6.510000 (  6.665572)
Multiple element splat     0.070000   0.000000   0.070000 (  0.072873)

Not like micro-optimizations matter...

0 comments: