3

Is there any way to check/compare JavaScript codes' performances on my pc/browser?

Like,

Method 1:

var x = 3;
if (x === 1) {
  console.log(1);
} else {
  console.log(2);
}

Method 2:

var x = 3;
switch (a) {
  case 1: 
    console.log(1);
    break; 
  default: 
    console.log(2);
  }

Here, 'Method 1' and 'Method 2' both does the same thing, and if I search on the internet there might be several benchmarks to prove which method is faster/efficient.

But I want to check it myself (offline methods, i mean on my pc would be better for me).

Thanks :)

7
  • Check jsperf.com Commented Aug 9, 2015 at 8:50
  • Thanks, I've seen that, but is there any way I can do that on my browser/pc? Like Chrome Dev Tools has a lots of features, Does it supports those performance checking too? Commented Aug 9, 2015 at 8:53
  • @MARUF: Chrome's dev tools have performance stuff in them, yes, but as a one-off you're not going to see enough difference to measure. You'd have to use a loop, which opens you up to all kinds of problems because what you're testing is synthetic rather than real. Commented Aug 9, 2015 at 9:02
  • @MARUF: FYI, unlike C or Java, switch and if/else if/else are effectively the same thing in JavaScript. I'd expect your two code examples above, if they were identified as performance-critical, to end up being compiled to the same machine code by Chrome's V8 engine, for instance. Commented Aug 9, 2015 at 9:04
  • @MARUF: Instead of micro-optimizing ahead of time, respond to performance issues in the real code if and when they occur. Commented Aug 9, 2015 at 9:04

1 Answer 1

1

Yes, you can check the performance by using "console.time"

Try this,

For Method 1 :

console.time('Method #1');

var x = 3;
if (x === 1) {
  console.log(1);
} else {
  console.log(2);
}

console.timeEnd('Method #1');

For Method 2:

console.time('Method #2');

var x = 3;
switch (a) {
 case 1: 
   console.log(1);
 break; 
default: 
   console.log(2);
}

console.timeEnd('Method #2');
Sign up to request clarification or add additional context in comments.

4 Comments

I doubt that that will yield any reasonable timings. Better run each method a few 100K times
@robertklep it definitely will not, since modern engines (de)optimise as code warms up.
@zerkms yeah, even those "100K" iterations will probably not yield any really useful results with this code.
@robertklep there is a good chance both will be optimised to something very similar if not identical :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.