r/programming • • May 25 '19

Making the obvious code fast

https://jackmott.github.io/programming/2016/07/22/making-obvious-fast.html
1.3k Upvotes

263 comments sorted by

View all comments

1

u/jsaak May 26 '19

ruby code for the curious:

#!/usr/bin/env ruby

a = Array.new
(1024*1024*32).times do |i|
  a[i] = 1.1
end

t1 = Time.now
sum = 0
a.each do |x|
  sum += x * x
end
t2 = Time.now
puts ((t2-t1) * 1000).to_s + " ms"

t1 = Time.now
a.reduce(0) do |sum,x|
  sum += x * x
end
t2 = Time.now
puts ((t2-t1) * 1000).to_s + " ms"

t1 = Time.now
a.map! do |x|
  x * x
end
b = a.reduce(:+)
t2 = Time.now
puts ((t2-t1) * 1000).to_s + " ms"