迭代比线性代码慢吗?哪一个更好?
我在过去很多天在我的心中有一个问题,那就是在ruby中编写代码时,线性代码比迭代更快,更可取。
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:
方法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."
那么,我想知道哪一个更好,根据我的观点,我认为第二个将花费更少的时间和记忆。但是我想确认。
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.
第二个例子违反了 DRY(不要重复自己)原则,是一个小的维护问题。
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)