Self-Learn Yourself Scala in 21 Blogs – #7
Missed the previous blogs have a quick look with Self-Learn Yourself Scala in 21 Blogs (#1, #2, #3, #4, #5, #6). In this blog let’s understand evaluation strategies in Scala programming.
There are two common evaluations strategies in scala. Call by Value and call by name. The End result of both the strategies will result in same final value as long as both the evaluation terminates.
Call by value has advantage that it evaluates every function argument only once. Call by name has the advantage if a function argument is not evaluated. We will see few examples to understand this better.
Let’s define a function as below
Def demo(x:Int, y:Int) = x * x
Now we apply some arguments to above function and understand which strategy works faster.
Demo(2,3)
CBV(Call By Value) :
Demo(2,3)
2 * 2
4
3 steps.
CBN(Call By Name):
Demo(2,3)
2 * 2
4
3 steps
for this argument both strategies take same amount of steps.
Demo(2+4,8)
CBV:
Demo(2+4,8)
Demo(6,8)
6 * 6
36
4steps
CBN:
Demo(2+4,8)
(2+4) * (2+4)
6* (2+4)
6 * 6
36
5steps
CBV scores better since it has to evaluate the argument only once whereas in CBN it has to do the same computation again and again.
Demo(7,2*4)
CBV:
Demo(7,2*4)
Demo(7,8)
7 * 8
56
4steps
CBN:
Demo(7,2*4)
7 * 7
49
3steps
CBN does it better since there is unwanted evaluation of second argument but CBV does evaluate the arguments prior to actual computation.
Demo(3+4,2*4)
CBV:
Demo(3 + 4,2*4)
Demo(7,2*4)
Demo(7,8)
7 * 7
49
5steps
CBN:
Demo(3 + 4,2 * 4)
(3+4) * (3+4)
7 * (3+4)
7 * 7
49
5 steps.
Both approaches take same number of steps as the CBV does unwanted computation for second argument and CBN does compute the first argument twice.
Scala by default uses Call By Value evaluation strategies as it provides distinct advantage in case of exponential arguments (e,g: x^10) by avoiding lengthy computations again and again if that argument is used more than once in function body.
But it provides an option to override it to Call By Name, as follows:
def Demo(x: => Int)
Infact this forms the basis for lazy evaluation strategy in Scala which is quite important for bigger collections.
Written By – Ramji Viswanathan, Big Data Lead, Capgemini
Interesting? Please subscribe to our blogs at www.dataottam.com, to keep you trendy and for future reads on Big Data, Analytics, and IoT.
As, always please feel free to suggest or comment coffee@dataottam.com.