可能重复:
迭代是否比线性代码慢?哪一个更可取?
过去很多天我有一个问题,在用 ruby 编写代码时,线性代码是否比迭代更快、更可取?
让我举个例子。有一个相同功能的代码块以两种不同的方式编写:
方式一:
['dog', 'cat', 'tiger'].each do |pet_name|
puts "I have many pets, one of them is #{pet_name}."
end
方式二:
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."
所以,我想知道哪个更好更可取?根据我的观点,我认为第二个将花费更少的时间和记忆。但我想确认。