Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array optimization: what is more expensive?

Which of the following pieces of code is more expensive?

x = my_array.inject {|sum,i| int+=i }

or

x = eval(my_array.join('+'))
like image 473
gmile Avatar asked Sep 11 '26 10:09

gmile


1 Answers

Try them:

#!/usr/local/bin/ruby -w
require 'benchmark'
iterations = 1000000

Benchmark.bmbm do |bench|
  numbers = (1..100).to_a

  bench.report('inject') do
    x = numbers.inject { |sum, num| sum + num }
  end
  bench.report('eval') do
    x = eval(numbers.join('+'))
  end
end

Which gives:

telemachus ~ $ ruby bench.rb 
Rehearsal ------------------------------------------
inject   0.000000   0.000000   0.000000 (  0.000029)
eval     0.000000   0.000000   0.000000 (  0.000261)
--------------------------------- total: 0.000000sec

             user     system      total        real
inject   0.000000   0.000000   0.000000 (  0.000047)
eval     0.000000   0.000000   0.000000 (  0.000186)

But actually, I think you're micro-optimizing. I would use inject unless it was grossly inefficient, since it's what the method was built for.

Also I think that your code for inject has two issues. First, you don't mean int, you mean sum. Second, you can simply add the items, rather than use +=. The first paramter to inject automatically accumulates value.

like image 194
Telemachus Avatar answered Sep 13 '26 00:09

Telemachus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!