1. 程式人生 > >幾種動態調用js函數方案的性能比較

幾種動態調用js函數方案的性能比較

switch 動態 UNC ima for clas har col alt

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title></title>
  </head>
  <body>
    <script>
      function f1() {
        return 1 + 1;
      }

      function f2() {
        return 1000 + 3002 + "sxdd";
      }

      // 方案1
console.time("t1"); for (let i = 0; i < 10000000; i++) { const name = Math.random() > 0.5 ? "f1" : "f2"; window[name](); } console.timeEnd("t1"); // 方案2 console.time("t2"); for (let i = 0; i < 10000000; i++) { const name = Math.random() > 0.5
? "f1" : "f2"; switch (name) { case "f1": f1(); break; case "f2": f1(); break; } } console.timeEnd("t2"); // 方案3 console.time("t3"); const map = { f1, f2 }; for
(let i = 0; i < 10000000; i++) { const name = Math.random() > 0.5 ? "f1" : "f2"; map[name](); } console.timeEnd("t3"); </script> </body> </html>

chrome:

技術分享圖片

火狐:

技術分享圖片

性能排序都是 方案2 > 方案3 > 方案1

簡潔靈活程度的話,正好與性能相反(魚與熊掌不可兼得) 方案1 > 方案3 > 方案2

不過不同瀏覽器內核性能差異較大,應該與瀏覽器內核優化有關

在chrome中,方案1性能極差,高性能場景慎用

幾種動態調用js函數方案的性能比較