前言
之前一直没有去研究try catch对代码运行的性能影响,只是一直停留在了感觉上,正好最近开会交流学习的时候,有人提出了相关的问题。借着周末,正好研究一番。
前端线上脚本错误的捕获方法:
window.JSTracker=window.JSTracker||[];try{//your code}catch(e){JSTracker.push(e);throwe;//建议将错误再次抛出,避免测试无法发现异常}
设计实验方式
简单的设计方案也就是对比实验。
空白组1:[无 try catch 的情况下对数据取模1千万次耗时]
<!DOCTYPEhtml><html><head><title>1无trycatch的情况耗时</title><script>!function(){//无try catch的情况耗时vart=newDate();//耗时代码开始for(vari=0;i<100000000;i++){varp=i%2;}//耗时代码结束document.write(newDate() t);}();</script></head><body></body></html>
参照组2:[将耗时代码用 try 包围,内联耗时代码]
<!DOCTYPEhtml><html><head><title>2在try中内联代码的耗时情况</title><script>!function(){//在 try 中内联代码的耗时情况vart=newDate();try{//耗时代码开始for(vari=0;i<100000000;i++){varp=i%2;}//耗时代码结束thrownewError();}catch(e){}document.write(newDate() t);}();</script></head><body></body></html>
参照组3:[将耗时代码用 try 包围,外联耗时代码]
<!DOCTYPEhtml><html><head><title>3在try中内联代码的耗时情况</title><script>!function(){functionrun(){//耗时代码开始for(vari=0;i<100000000;i++){varp=i%2;}//耗时代码结束}//在 try 中内联代码的耗时情况vart=newDate();try{run();thrownewError();}catch(e){}document.write(newDate() t);}();</script></head><body></body></html>
参照组4:[将耗时代码用 catch 包围,内联耗时代码]
<!DOCTYPEhtml><html><head><title>4在catch中内联代码的耗时情况</title><script>!function(){//在 catch 中内联代码的耗时情况vart=newDate();try{thrownewError();}catch(e){//耗时代码开始for(vari=0;i<100000000;i++){varp=i%2;}//耗时代码结束}document.write(newDate() t);}();</script></head><body></body></html>
参照组5:[将耗时代码用 catch 包围,外联耗时代码]
<!DOCTYPEhtml><html><head><title>5在catch中内联代码的耗时情况</title><script>!function(){functionrun(){//耗时代码开始for(vari=0;i<100000000;i++){varp=i%2;}//耗时代码结束}//在 catch 中内联代码的耗时情况vart=newDate();try{thrownewError();}catch(e){run();}document.write(newDate() t);}();</script></head><body></body></html>
运行结果(只选取了 Chrome 作为示例)