0

I tried comparing two functions which perform the same task:

Number.prototype.getReverse = function() {
  let reverseNum = 0
  let num = this
  while(num > 0) {
    reverseNum = (10 * reverseNum) + (num % 10)
    num = Math.floor(num / 10)
  }
  return reverseNum
}
const numb = 1234567
console.time()
console.log(numb.getReverse())
console.timeEnd()

function getReverseNum(num) {
  let reverseNum = 0
  while (num > 0) {
    reverseNum = (10 * reverseNum) + (num % 10)
    num = Math.floor(num / 10)
  }
  return reverseNum
}

console.time()
console.log(getReverseNum(numb))
console.timeEnd()

The prototype of the Number object took far longer:

7654321
default: 0.42ms
7654321
default: 0.109ms

I was curious as to whether anyone might know why this is. Does it have to do with the way JavaScript accesses the function through the object Number?

  • One trial is not enough to draw conclusions from. – SuperStormer Feb 25 '22 at 00:49
  • A decent benchmark should be measuring differences of something closer to the order of seconds, at least, not just milliseconds - and the compared code should not run one after the other, but in completely separate environments. And even then https://mrale.ph/blog/2012/12/15/microbenchmarks-fairy-tale.html – CertainPerformance Feb 25 '22 at 00:49
  • 1
    You aren't measuring "time complexity" or "big-O". You're using the same value of `numb` both times. To study big-O, you need to see how the running time changes as `numb` changes. – Raymond Chen Feb 25 '22 at 00:59
  • Like Raymond said, you're not measuring complexity (which even cannot be "measured", it can only be determined through analysis of the algorithm - and it's actually the same for both of your implementations). What you are measuring is the performance (or: speed) of your two implementation. And no, it's not slower because it's accessing the function differently, it's slower because `numb` is a number but `this` is an object. – Bergi Feb 25 '22 at 01:09

0 Answers0