Skip to content

Instantly share code, notes, and snippets.

@ryandotsmith
Created August 6, 2010 05:09
Show Gist options
  • Save ryandotsmith/510875 to your computer and use it in GitHub Desktop.
Save ryandotsmith/510875 to your computer and use it in GitHub Desktop.
ruby #inject vs. #sum
data = (1..1_000).to_a
measure "sum" do
data.sum { |n| n }
end
measure "inject" do
data.inject(0) { |sum, element| sum + element}
end
=begin
=============
Date: August 06, 2010
System Information
------------------
Operating System: Mac OS X 10.6.4 (10F569)
CPU: Intel Core i7 2.66 GHz
Processor Count: 2
Memory: 4 GB
ruby 1.9.1p378 (2010-01-10 revision 26273) [i386-darwin10.4.0]
"inject" is up to 48% faster over 1,000 repetitions
---------------------------------------------------
inject 0.0993571281433105 secs Fastest
sum 0.194322109222412 secs 48% Slower
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment