<!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函数方案的性能比较
原文地址:https://www.cnblogs.com/DarkMaster/p/10190497.html