From: Kaspar Schiess Date: 2004-04-22T20:28:43+09:00 Subject: Re: efficient collect+compact ? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Martin Pirker wrote: | I read Array and Enumerable docs, have I missed something[1] or does | a straight "collect everything but nil" function not exist? The function select collects everything but false elements, the function reject does the opposite. I am surprised that this did not come up as the first answer: (insert this into code posted earlier on thread) b.report 'select+collect' do ~ ary= Z.select{ |x| x%2 != 0 }.collect{|x| x+10} ~ p ary[0] ~ end ~ b.report 'reject+collect' do ~ ary= Z.reject{ |x| x%2 == 0 }.collect{|x| x+10} ~ p ary[0] ~ end Performance comparison yields: ~ user system total real map!+compact! ~ 1.202000 0.000000 1.202000 ( 1.422000) map+compact ~ 0.651000 0.010000 0.661000 ( 0.711000) inject ~ 5.378000 0.000000 5.378000 ( 5.608000) external ~ 0.781000 0.000000 0.781000 ( 0.781000) external for ~ 0.741000 0.000000 0.741000 ( 0.741000) select+collect ~ 0.871000 0.000000 0.871000 ( 0.872000) reject+collect ~ 0.831000 0.000000 0.831000 ( 0.831000) for a million elements. Ranking as follows (from this one test): map+compact external for external reject+collect select+collect map!+compact! inject I take the following lessons home: - - map/collect is fast, since it preallocates arrays. - - external for is fast, no allocating of blocks - - inject is evil because of its implementation ruby 1.8.1 (2004-01-27) [i386-mswin32] btw. Anyone more explanations ? kaspar - code philosopher - -- stolen off the net -- A rock pile ceases to be a rock pile the moment a single man contemplates it, bearing within him the image of a cathedral. ~ -- Antoine de Saint-Exupery -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.4 (MingW32) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFAh6ziFifl4CA0ImQRAgH2AJ90JK4UiUY5y260ml2jurvgNUtqgQCgnwzH cKuNzETyV+zcgXAjcWnwh4Q= =DA0A -----END PGP SIGNATURE-----