[Solved] Is iteration slower than linear code? Which one is preferable?


Sequential logic is faster (see the benchmark below the fold), but it almost never matters. The clearer and more maintainable code should always be selected. Only a demonstrated need should cause one to cease optimizing for the programmer and begin optimizing for the machine. By demonstrated, I mean measured–you ran it and found it to be too slow.

The second example violates the DRY (Don’t Repeat Yourself) principle and is a minor maintenance problem.


require 'benchmark'

LOOPS = 100000

Benchmark.bm(10) do |x|
  x.report('iteration') do
    LOOPS.times do
      ['dog', 'cat', 'tiger'].each do |pet_name|
        "I have many pets, one of them is #{pet_name}."
      end
    end
  end
  x.report('sequence') do
    LOOPS.times do
      "I have many pets, one of them is dog."
      "I have many pets, one of them is cat."
      "I have many pets, one of them is tiger."
    end
  end
end

# =>                  user     system      total        real
# => iteration    0.200000   0.000000   0.200000 (  0.202054)
# => sequence     0.010000   0.000000   0.010000 (  0.012195)

solved Is iteration slower than linear code? Which one is preferable?