假设我有一个类型type 'a tree = Node of int * 'a * 'a tree
int部分是rank 。
我还有一个函数let rank = function Node (r, _, _) -> r 。
假设在我的实际代码中,我有很多地方需要访问节点的rank ,并且在很多时候,相同节点的rank 。
我的问题是,我是否应该直接使用rank t函数,或者我应该将r的等级赋予r ,然后使用r ?
例如,我可以做
if rank t1 < rank t2 then Node (rank t1 + 1, 5, t1) else Node (rank t2 + 1, 5, t2)要么
let r1 = rank t1 in let r2 = rank t2 in if r1 < r2 then Node (r1+1, 5, t1) else Node (r2, 5, t2)什么是性能差异? 哪种方式更好,为什么?
Let's say I have such a type type 'a tree = Node of int * 'a * 'a tree
The int part is the rank.
Also I have a function let rank = function Node (r, _, _) -> r.
Suppose in my real code, I have lots of places that need to access the rank of a node, and much of the time, the rank of same nodes.
My question is that Should I always use rank t function directly or should I give the rank of a t to, say, r, then use r?
For example, I can do
if rank t1 < rank t2 then Node (rank t1 + 1, 5, t1) else Node (rank t2 + 1, 5, t2)or
let r1 = rank t1 in let r2 = rank t2 in if r1 < r2 then Node (r1+1, 5, t1) else Node (r2, 5, t2)What is the performance diff? And which way is better and why?
最满意答案
我认为使用let来避免计算两次排名更好。 我不认为OCaml编译器优化两次调用相同的函数; 它需要某种效果分析。
我会很高兴错了;)
I think using let to avoid computing the rank twice is better. I don't think the OCaml compiler optimizes calling the same function twice; it would require some kind of effect analysis.
I'd be glad to be wrong though ;)
更多推荐
发布评论