From: Robert Klemme Date: 2004-09-06T02:25:13+09:00 Subject: Re: autochomp? >>> #---- end filetest.rb ----- >>> >>> $ seq 10000 > testfile.txt >>> $ ruby filetest.rb >>> readlines: 0.050000 0.010000 0.060000 ( 0.085483) >>> inject: 0.130000 0.010000 0.140000 ( 0.172144) >>> foreach: 0.080000 0.000000 0.080000 ( 0.112690) >> >> That's really interesting. Did you also test with a real world file (a >> file >> with longer lines presumably)? Interestingly enough, changing the block >> of >> #inject does make it nearly as fast as readlines: > > What's the interesting bit? The impact of the two statements vs. one statement in the block plus that - once again - intuition is proven wrong. :-) > "readlines" is probably quicker than "inject" since there are less > method calls. In "inject" and "foreach" (and "inject2" and "foreach2" > in your later post), there are two method calls in the block: chomp! > and <<. In "readlines" there's only 1. All that pushing and popping > of ruby stack frames, method name looking up... it all adds up, more > so, evidently, than walking the array an extra time. > > (Also note that "foreach" won't work right if chomp! returns nil, which > it will on the last line if there's no newline @ EOF.) Yes, that was exactly the reason why I first used "line.chomp!; ar << line". But I wanted to make it comparable so I added the other variant. Kind regards robert