1

Is there any way to compare execution time of two methods?

For example I wonder which method is faster: querySelector() or getElementById(). Theoretically, I guess, time should be the same. But what if i want to check it in practice? Is any way to execute first method and check how much time it took, next doing the same with second method, and then to compare two results?

Stan
  • 86
  • 1
  • 6
  • Search on "benchmarking javascript" in general. https://stackoverflow.com/q/1003855/153197 Questions should show you did some research before asking. –  Aug 26 '17 at 14:14
  • Possible duplicate of [howto benchmark javascript code?](https://stackoverflow.com/questions/1003855/howto-benchmark-javascript-code) – Muthu Kumaran Aug 26 '17 at 14:18
  • jdv that's it! thank you! Muthu Kumaran yes, i didn't know this term. – Stan Aug 26 '17 at 14:19

3 Answers3

0

Some browser like Chrome, Chromium, Mozilla supports profiling tools. You may use that

And you could do it manually in the classic sense

  • measure start time
  • repeat empty loop many times
  • measure the difference, that is the overhead of the loop.

  • measure start time

  • repeat your code many times
  • measure the difference, subtract the overhead of the loop and divide by the number of times.
stefan bachert
  • 9,413
  • 4
  • 33
  • 40
0

Micro benchmarks don't always give you an accurate representation of the cost of the implementation in a real scenario. Even if you run the exact same machine code, the code will be ready in cache and that might not be the case in your use case.

The problem is further complicated by the fact that modern javascript engines optimise the hell out of hot loop code, so the micro-benchmark machine code will probably be a lot different. The only way is to implement both (or more) methods and test in your particular use case with similar loads.

Most of the times though, searching around a bunch (in places like jsperf) will give you an idea and tell you if one implementation is drastically more performant.

jaihindhreddy
  • 358
  • 2
  • 7
0
var startTime = new Date().getTime();
document.querySelector("element");
var endTime = new Date().getTime();
console.log(endTime - startTime)


var startTime = new Date().getTime();
document.getElementById("element");
var endTime = new Date().getTime();
console.log(endTime - startTime)

By this you can seperately get time duration in milliseconds

thinuwan
  • 631
  • 2
  • 8
  • 20