Array optimization: which is more expensive?

Which of the following code snippets is more expensive?

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

      

or

x = eval(my_array.join('+'))

      

+2


source to share


2 answers


Try:

#!/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

      

What 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 are micro-optimizing. I would use inject

it if it wasn't grossly inefficient, as this was the method the method was created for.

Also I think your code for inject

has two problems. First, you don't mean int

, you mean sum

. Second, you can just add elements, not use +=

. The first parameter inject

automatically accumulates the value.

+12


source


As a rule of thumb, eval code is always slower than its reasonable alternative (as in this case). It is also potentially insecure if it handles user input.



And just for writing in Rails (or after require 'activeresource'

) you can also use a method numbers.sum

that is about as fast as INCHO and is more readable.

+1


source







All Articles