I have a question in my mind from last many days, that while writing a code in ruby, is the linear code is faster and preferable than an iteration?
Let me have an example. There is a block of code for same functionality written in two different ways:
Way 1:
['dog', 'cat', 'tiger'].each do |pet_name|
puts "I have many pets, one of them is #{pet_name}."
end
Way 2:
puts "I have many pets, one of them is dog."
puts "I have many pets, one of them is cat."
puts "I have many pets, one of them is tiger."
So, I want to know which one is better and preferable? As per my view, I think 2nd one will take less time and memory. But I want to confirm.
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.