Abstract
- Lazy evaluation refers to delaying the computation of an Expression until its value is actually needed, and avoid repeated computation with the help of Memoization
Lazy Evaluation with Java
- The code example below is around
showSystemInfo()which prints out the system information likeCPU,RAM&SSDif thebatteryLevelis>=20. Otherwise, it should print out anything to console
Without lazy evaluation
- We have to retrieve the system information even when the
batteryLevelis<20, this is wasted computation because we canβt print out the system information when thebatteryLevel<20!
With lazy evaluation
- With the help of Functional Interface and Java Lambda, we are able to treat the Function that handles system information retrieval as First-class Citizen Function, passing them into the
showSystemInfowhich decides if it needs to retrieve the system information depends on thebatteryLevel. We only retrieve the system information when we have enough battery
Important
We can also make use of Memoization if the result of computation remains the same all the time.
