OCaml中的模式匹配性能(Pattern Matching performance in OCaml)

编程入门 行业动态 更新时间:2024-10-15 02:24:28
OCaml中的模式匹配性能(Pattern Matching performance in OCaml)

假设我有一个类型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 ;)

更多推荐

本文发布于:2023-07-15 17:30:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1116664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:性能   模式   OCaml   performance   Matching

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!