Clojure:减少vs.应用 [英] Clojure: reduce vs. apply

查看:97
本文介绍了Clojure:减少vs.应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解 reduce 之间的概念差异应用

(reduce + (list 1 2 3 4 5))
; translates to: (+ (+ (+ (+ 1 2) 3) 4) 5)

(apply + (list 1 2 3 4 5))
; translates to: (+ 1 2 3 4 5)

然而,哪一个更为惯用的clojure?它有什么区别单向或其他?从我的(有限的)性能测试,看来 reduce 有点快。

However, which one is more idiomatic clojure? Does it make much difference one way or the other? From my (limited) performance testing, it seems reduce is a bit faster.

推荐答案

reduce apply 当然只是等效的(根据返回的最终结果)它们需要在可变的情况下看到它们的所有参数。当它们在结果上等同时,我会说 apply 总是完全惯用的,而 reduce 是等效的 - - 并且可能会刮掉眨眼的一小部分 - 在很多常见的情况下。以下是我相信这个的理由。

reduce and apply are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I'd say that apply is always perfectly idiomatic, while reduce is equivalent -- and might shave off a fraction of a blink of an eye -- in a lot of the common cases. What follows is my rationale for believing this.

+ 本身是以 reduce 用于变量 - 实例(多于2个参数)。事实上,这似乎是一个非常明智的默认方式去任何可变的关联函数: reduce 有可能执行一些优化以加快速度 - 也许通过类似 internal-reduce 的东西,一个1.2新奇最近在主人禁用,但希望在未来重新引入 - 这将是愚蠢的复制在每个函数可能会受益于他们在vararg的情况。在这种常见的情况下, apply 只会增加一点开销。 (注意这不是真正担心的。)

+ is itself implemented in terms of reduce for the variable-arity case (more than 2 arguments). Indeed, this seems like an immensely sensible "default" way to go for any variable-arity, associative function: reduce has the potential to perform some optimisations to speed things up -- perhaps through something like internal-reduce, a 1.2 novelty recently disabled in master, but hopefully to be reintroduced in the future -- which it would be silly to replicate in every function which might benefit from them in the vararg case. In such common cases, apply will just add a little overhead. (Note it's nothing to be really worried about.)

另一方面,复杂函数可能利用一些不够一般性的优化机会来构建into reduce ;那么 apply 会让你利用这些,而 reduce 可能会减慢你的速度。在实践中后一种情况的一个很好的例子是由 str 提供:它在内部使用 StringBuilder 从使用应用而不是减少

On the other hand, a complex function might take advantage of some optimisation opportunities which aren't general enough to be built into reduce; then apply would let you take advantage of those while reduce might actually slow you down. A good example of the latter scenario occuring in practice is provided by str: it uses a StringBuilder internally and will benefit significantly from the use of apply rather than reduce.

所以,我会说怀疑使用 apply ;如果你碰巧知道它不是在购买你 reduce (并且这不会很快改变),请随意使用 reduce 可以减少这种不必要的开销,如果你愿意的话。

So, I'd say use apply when in doubt; and if you happen to know that it's not buying you anything over reduce (and that this is unlikely to change very soon), feel free to use reduce to shave off that diminutive unnecessary overhead if you feel like it.

这篇关于Clojure:减少vs.应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆