Search code examples
javascriptmemory-managementbrowsermemory-efficient

Best way to use modulus and substring in javascript


I want to get last two character of year. e.g. input= 2016 then output= 16

var year = 2016;

Two approach:

  1. Use modulus: year%100
  2. Use substring: year.toString().substring(2,4)

Which one is the best approach to use, in term of memory and computation cost?


Solution

  • This could be dependent on the ECMAScript engine but here's my guesstimate based on looking at the implementation in JavaScriptCore (JSC), which is the JavaScript implementation of WebKit. The following time complexities are total guesses on my part...

    The substring() method appears to have a time complexity of 0(n) as I believe it loops through the characters based on the start and end arguments.

    The modulo method is most likely 0(n/m) time complexity, where n is the number being divided and m is number used to divide by. Dividing a large number by a small number will take more iterations. There may be some optimizations for certain cases, like dividing by 0, 1, etc.

    In this particular case, the requirement to convert the year to a string using toString() most likely makes the modulo method slightly more performant. Any gains are probably small and undetectable.

    However, there's a more important factor to consider. The modulo method might cause issues in special cases. For example, the year 2000 will result in 0.

    > 2000%100
    < 0
    

    This might cause issues with your script.

    In the end the substring() method is the safer, nearly equal performant, solution.