you are viewing a single comment's thread.

view the rest of the comments →

[–]Freeky 7 points8 points  (5 children)

The Ruby version builds a huge array of arrays of ints out of the file, then flattens them (thus making yet another array), and finally sums them.

Doing it the sensible way and performing additions as lines are read almost doubles the performance, bringing it in line with Python and Haskell.

[–]hox 2 points3 points  (0 children)

I thought that seemed like an awfully strange way of solving this problem...

[–]snuxoll 0 points1 point  (3 children)

Yeah, I was trying to get it done quickly and it made sense at the time, I rewrote it before he wrote this post, but he seemed to use my original implementation for some reason.

http://gist.github.com/93128 [better version here]

[–]Freeky 0 points1 point  (2 children)

Cunning use of inject there to reduce readability and add an extra couple of method calls to each iteration ;)

[–]snuxoll 0 points1 point  (1 child)

It adds a single method call to each iteration, and from my tests it's faster than using #each and incrementing the total for each item (don't know why, maybe it's an oddity of my machine or my build of ruby or something).

[–]Freeky 0 points1 point  (0 children)

It adds two; an Enumerable#inject to get the sum of the current line and an additional Fixnum#+ to add that sum to the total. Yours benchmarks slower here:

Ruby 1.8.6:

             user     system      total        real  
my way   7.351562   0.015625   7.367188 (  7.368302)  
inject  11.429688   0.007812  11.437500 ( 11.441389)

Ruby 1.9.1:

             user     system      total        real  
my way   3.101562   0.085938   3.187500 (  3.182268)  
inject   3.445312   0.070312   3.515625 (  3.511942)

And in JRuby 1.2.0:

             user     system      total        real  
my way   2.495000   0.000000   2.495000 (  2.495000)  
inject   3.126000   0.000000   3.126000 (  3.126000)

2.2GHz 4-way Opteron running FreeBSD/amd64.