How do you performance test JavaScript code?

前端 未结 22 1129
难免孤独
难免孤独 2020-11-22 04:18

CPU Cycles, Memory Usage, Execution Time, etc.?

Added: Is there a quantitative way of testing performance in JavaScript besides just perception of how fast the code

22条回答
  •  情话喂你
    2020-11-22 04:32

    I do agree that perceived performance is really all that matters. But sometimes I just want to find out which method of doing something is faster. Sometimes the difference is HUGE and worth knowing.

    You could just use javascript timers. But I typically get much more consistent results using the native Chrome (now also in Firefox and Safari) devTool methods console.time() & console.timeEnd()

    Example of how I use it:

    var iterations = 1000000;
    console.time('Function #1');
    for(var i = 0; i < iterations; i++ ){
        functionOne();
    };
    console.timeEnd('Function #1')
    
    console.time('Function #2');
    for(var i = 0; i < iterations; i++ ){
        functionTwo();
    };
    console.timeEnd('Function #2')
    

    Results Look like this

    Update (4/4/2016):

    Chrome canary recently added Line Level Profiling the dev tools sources tab which let's you see exactly how long each line took to execute!

提交回复
热议问题