Ruby Map/Reduce 函数一定高效吗?
b1 = Time.now
puts (1..100000).inject(0) { |x, y| x + y }
a1 = Time.now
puts "Time for inject: #{a1 - b1}"
b2 = Time.now
sum = 0
(1..100000).each do |value|
sum += value
end
puts sum
a2 = Time.now
puts "Time for each: #{a2 - b2}"
上面的 Ruby 代码比较了两种对整数求和的方法。令我惊讶的是,更优雅的 inject 或 reduce 方法优于另一种方法。为什么会这样呢?为什么人们要费心使用低效的inject或reduce?仅仅因为它优雅?
PS:感谢所有鼓舞人心的答案。我的目的是询问导致差异的幕后发生的事情。
b1 = Time.now
puts (1..100000).inject(0) { |x, y| x + y }
a1 = Time.now
puts "Time for inject: #{a1 - b1}"
b2 = Time.now
sum = 0
(1..100000).each do |value|
sum += value
end
puts sum
a2 = Time.now
puts "Time for each: #{a2 - b2}"
The above Ruby code compares two ways of summing up integers. To my surprise, the more elegant inject or reduce approach is outperformed by the other. Why is that the case? Why do people bother using the inefficient inject or reduce? Simply because it's elegant?
PS: Thanks for all the inspiring answers. My intention was to ask what's going on behind the scene that results in the differences.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在这种情况下,我会进行一些数学计算:
结果是:
更好的数学总是更快:)
I would go with a little math in this case:
And the result is:
A better math is always faster :)
是的,代码可读性比微优化更重要。即使在计算数百万个元素的总和时,差异也几乎不明显。此外,这两种方法的复杂度都是
O(n)
,因此随着元素数量的增加,两种方法都不会明显优于另一种方法。正如其他人指出的那样,
inject(:+)
仍然更快一些。即使不是,也请选择最容易看到的一个,并且不必担心性能上的微小差异。这可能不会成为您的应用程序的瓶颈。结果:
Yes, code readability is more important than micro-optimisations. The difference is barely noticeable, even when taking the sum of millions of elements. Also, both methods are
O(n)
, so neither will significantly outperform the other as the number of elements increases.As others have pointed out,
inject(:+)
is a little faster still. Even if it weren't, pick the one that is easiest on the eye, and don't worry about tiny differences in performance. This will probably not be the bottleneck in your application.Results:
请尝试以下操作:就
我个人而言,我追求优雅,如果单行注入可以替换 3 行,只要它不会变得混乱,我就会选择注入。
Try the following instead:
Personally I go for elegance, if a single line inject can replace a 3 lines each as long as It doesnt' get messy I'd go with inject.
@derp是对的。我建议您下次使用基准测试模块,例如:
@derp is right. I recommend you to use the benchmark module the next time like:
有趣的是,之前的大部分或全部答案可能都假设了 ruby 的最新主要版本(1.9)。在 1.8.7 中,这种差异更加明显:
在可读性和可读性方面完全一致。不过维护更重要。
It's interesting to note that most or all of the previous answers probably assumed the latest major version of ruby (1.9). In 1.8.7 this difference is more pronounced:
Absolutely agree on readability & maintenance being more important though.
Ruby 主要与性能无关。如果您想要表演,还有为此设计的其他语言。
Ruby 就是为了享受编写优雅代码的乐趣:)
Ruby is mostly not about performances. If you want performances there are other languages designed for that.
Ruby is all about the pleasure to write elegant code :)