Lazy 模块中有两种力量:
val force : 'a t -> 'a
force x forces the suspension x and returns its result. If x has already been forced, Lazy.force x returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. Raise Undefined if the forcing of x tries to force x itself recursively.
val force_val : 'a t -> 'a
force_val x forces the suspension x and returns its result. If x has already been forced, force_val x returns the same value again without recomputing it. Raise Undefined if the forcing of x tries to force x itself recursively. If the computation of x raises an exception, it is unspecified whether force_val x raises the same exception or Undefined.
似乎唯一的区别是
If the computation of x raises an exception, it is unspecified whether force_val x raises the same exception or Undefined.`
据我了解,我们不知道它是否会引发原始异常或
Undefined
如果我们使用 force_val
.那么这背后的意义何在?为什么要这样?我们可以从
force_val
获得任何好处?
最佳答案
我想这是出于性能目的。
如果您关心得到相同的错误,请使用 force
.如果您不想但想要更好的性能,请使用 force_val
.
如您所见here , force
与 force_val
做同样的事情但在发生异常时执行额外的内存访问。
阅读源代码并运行一些测试后,这两个函数的行为似乎与文档所说的不同:如果您只使用 force
,您将始终得到原始错误,但如果您使用 force_val
第一次调用将引发原始异常以及对 force_val
的所有后续调用。 或 force
将提高Undefined
.
编辑:实际上,我不确定使用 force_val
而不是 force
从 force
开始提高性能是原语和 force_val
不是。
关于ocaml - `Lazy.force` 和 `Lazy.force_val` 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23293234/