有什麼更好?如果:匹配預期字符串在技術上更有效嗎?
function a(){};
則更快處理此
if(typeof a == "function"){func(arg);}
或那樣嗎?
if(!(typeof a).search("f")){func(arg);}
我只問這個,因爲在我看來,比起整個字符串更容易匹配字符串的第一個符號,不是嗎?有興趣確保。
有什麼更好?如果:匹配預期字符串在技術上更有效嗎?
function a(){};
則更快處理此
if(typeof a == "function"){func(arg);}
或那樣嗎?
if(!(typeof a).search("f")){func(arg);}
我只問這個,因爲在我看來,比起整個字符串更容易匹配字符串的第一個符號,不是嗎?有興趣確保。
這裏是一個jsPerf測試http://jsperf.com/typeof-test12。
527,021,419
每秒操作。9,803,840
。這是一個巨大的保證金(第一個比第二快54倍在我的電腦上)。
你是不對的。 typeof a == "function"
更快。
快一點點(可能是你腦子裏想的是:
var a = function(){};
if((typeof a)[ 0 ] == 'f'){a()};
但下面的代碼是關於20比上面更快(鉻次):
var a = function(){};
if( a.constructor == Function){ a() };
其實不錯 – TERMtm
無論如何,感謝您鏈接到jsperf – TERMtm