Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `Lazy.force` and `Lazy.force_val`

There are two forces in Lazy module:


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.


It seems the only diff is

If the computation of x raises an exception, it is unspecified whether force_val x raises the same exception or Undefined.`

From my understanding, we don't know whether it will raise original exception or Undefined if we use force_val.

Then what's the point behind this? Why make it this way? Any good we can get from force_val?

like image 933
Jackson Tale Avatar asked Apr 25 '14 12:04

Jackson Tale


1 Answers

I guess it is for performance purpose. If you care about getting the same error, use force. If you don't but want better performance, use force_val.

As you can see here, force does the same thing as force_val but performs an extra access to memory in case an exception occurs.

After reading the source and running some tests, the behaviour of these two functions seems different from what the doc says : If you use only force, you will always get the original error but if you use force_val the first call will raise the original exception and all subsequent calls to force_val or force will raise Undefined.

EDIT: Actually, I'm not sure that using force_val instead of force improves performance since force is a primitive and force_val is not.

like image 86
Thomash Avatar answered Sep 30 '22 16:09

Thomash