可能重复:
Is iteration slower than linear code? Which one is preferable?
我最近几天在脑海里有一个问题,即在ruby中编写代码时,线性代码是否比迭代更快,更可取?
让我举个例子。有两种不同方式的相同功能代码块:
方式1:
['dog', 'cat', 'tiger'].each do |pet_name|
puts "I have many pets, one of them is #{pet_name}."
end
方式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."
所以,我想知道哪一个更好,更可取?根据我的观点,我认为第二个将花费更少的时间和记忆。但我想证实。