我現在就要結果!
即使變數尚未被呼叫做使用,也會先計算出來變數的值。
const a = 5 ;
const b = 10 ;
const result = a * b; // 即使result還未被使用,也會立即計算
console.log ( result ); // 列印結果 (50)
🟢 優點
🔴 缺點
有需要再叫我~
「計算結果」這件事被延遲到真正需要值的時候。
const lazyMultiply = ( a, b ) => () => a * b; // 回傳一個函數而不是立即計算
const lazyResult = lazyMultiply ( 5 , 10 ); // 尚未計算
console .log ( lazyResult ()); // 現在才計算 (50);
🟢 優點
🔴 缺點
如果資料量較小,使用eager 方法,否則將使用所有結果。
使用惰性求值可以提高效率,尤其是在處理大數據或只需要部分結果時。
https://dev.to/patoliyainfotech/lazy-vs-eager-evaluation-in-javascript-performance-trade-offs-3m7j
https://docs.gradle.org/current/userguide/lazy_eager_evaluation.html
https://khaisastudio.medium.com/eager-vs-lazy-approach-0b4b7ba63c90