In most programming languages, arguments passed to a function are evaluated before the function uses them, that is, they are evaluated eagerly.
To me, it seems like it would make much more sense to evaluate the arguments only once the function uses them, that is, lazily. This makes more sense to me because it seems like it would have a performance benefit: why evaluate things that are never even needed?
Moreover, suppose you wanted to implement an if function that accepts a boolean, and an object to return if the boolean is true, and another object to return if the boolean is false:
object if(bool condition, object valueIfTrue, object valueIfFalse) {
if(condition) return valueIfTrue;
return valueIfFalse;
}
In a language that eagerly evaluates arguments, both objects are always evaluated even though the function will always only need one of them, which, at best, incurs a slight unecessary overhead, and, at worst, causes an infinite loop.
That said, since most programming languages use eager evaluation of function arguments, I assume there must be a reason why it’s usually done that way. Is there some big benefit of eager evaluation here that I’m overlooking, is it just because it was easier to implement languages that way, is it just tradition, or what?
There are a couple reasons I’ve seen for eager evaluation, both of which are important:
Lazy evaluation can be a powerful tool, but it’s not without it’s costs. Purely functional languages tend to avoid problem #1 because they don’t have side effects (in general), but are still bitten by problem #2 at times. Languages that allow delayed evaluation (LISP macros are a form of this, though not the same as lazy evaluation) can have the best of both worlds, but at the cost of more effort on the programmer’s part.