2

I use console.time to show the time of the function. But I found that it shows different running time of the same function.

I have simplified my function as below:

const findIP = (res) => {
    let arr = []
    arr = res.split(',')
}
console.time('1')
findIP('1,2,3,4,5,6,7,8,9,0')
console.timeEnd('1')
console.time('2')
findIP('1,2,3,4,5,6,7,8,9,0')
console.timeEnd('2')

The time difference between the two is very large.

enter image description here

I have tried to run several times. And it still cost different time.

enter image description here

David Chan
  • 641
  • 1
  • 7
  • 10
  • If those units really are milliseconds, then that's a tiny difference. Only 0.181 ms different. – Tony Abrams Oct 04 '19 at 11:18
  • Then how can I compare different functions with tiny difference using console.time? – David Chan Oct 05 '19 at 01:28
  • Why would you need to see a tiny difference? Statistically there is no difference. – Tony Abrams Oct 05 '19 at 10:37
  • I just want to compare the efficiency of my code. Like https://stackoverflow.com/questions/58244744/how-to-compare-the-running-time-between-different-functions?noredirect=1#comment102861577_58244744 said. If it can not be the judgement, then what method can I use? – David Chan Oct 06 '19 at 06:39

2 Answers2

2

To quote the answer in the the following link:

If you run shorten multiple times, the V8 engine has a JIT compiler that will optimize that piece of code so it runs faster the next time.

https://stackoverflow.com/a/54601440

Bails
  • 21
  • 1
0

Try changing the argument value, for example

console.time('1')
findIP('1,2,3,4,5,6,7,8,9,0')
console.timeEnd('1')
console.time('2')
findIP('1,2,3,4,43,6,7,8,9,4')
console.timeEnd('2')

you will see approx equal time

Reason of that difference is: The browser cache

Simple Definition browser cache is a temporary storage area in memory or on disk that holds the most recently downloaded Web pages and/or calculated result.

Bilal Siddiqui
  • 3,579
  • 1
  • 13
  • 20