摘要:JavaScript eval
stopWatch('test eval',[function(){ //方法一,單純 eval var o,s="o=({a:[1,2,3],b:4})"; var parse =function(s){ eval(s); } parse(s); return o.b; },function(){ //方法二,new Function var s="o1=({a:[1,2,3],b:4})"; window.o1; var parse = Function(s); parse(s); return window.o1.b; },function(){ //方法三,呃…看起來就不會快XD var s="o2=({a:[1,2,3],b:4})"; window.o2; var parse = function(s){ var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; script.text = s; head.insertBefore( script, head.firstChild ); head.removeChild( script ); }; parse(s); return window.o2.b; }],10000); //測試用 function stopWatch(catgory, fn, runTimes){ runTimes = runTimes || 100000; var timeSt, result=[]; var start = function(){ timeSt = +new Date(); }; var end = function(){ return +new Date()-timeSt; } for(var f in fn){ var testFn = fn[f]; var testTimes = runTimes; var execResult; start(); while(testTimes--){ testFn(); }; execResult = testFn(); var timeSpend = end(); result.push({ fn:testFn.toString(), time:timeSpend+'ms', execResult:execResult}); } //return result; (function renderResult(result){ var div = document.createElement('div'); div.className = 'test_block'; var html = [catgory, ', 執行:', runTimes, '次']; html.push('<ul>'); for(var i in result){ var tmp = result[i] html.push('<li>'); html.push('<div class="fn_content"><pre>',tmp.fn,'</pre></div>', '<div class="time_spend">執行時間:',tmp.time,'</div>'); if(tmp.execResult) html.push('<div class="exec_result">執行結果:',tmp.execResult,'</div>'); html.push('</li>'); } html.push('</ul>'); div.innerHTML = html.join(''); document.body.appendChild(div); })(result); }
第二跟第三種函數好像只能用全域變數去接…這種 CODE我自己都不喜歡看到,速度慢,程式又醜,我想不到值得利用的場合。好吧,這種測試本來就是寫自己開心的XD,想到或看到不同的寫法,總會想試試看有沒有比較好,這樣一直累積…喜歡這種不斷改善、進步的感覺。