-2

I am in the middle of creating a calendar in javascript but am contemplating using the date functions to retrieve values or splitting the date string to retrieve values. I tried looking up the big o for these functions but have not found any. I want to know what is fastest.

For example

var date = new Date();
date.toString().split(" ")[1]; //this will get month name

vs

var date = new Date();
date.getMonth() //this will get month

they might not be the same but my question is which one is faster. edit i forgot toString.

  • I guess that spliting a string is faster but probably sure that the getMonth() method does the same internally – nazimboudeffa Dec 30 '20 at 23:08
  • 1
    [Why don't you test it yourself](https://stackoverflow.com/questions/111368/how-do-you-performance-test-javascript-code)? – Ivar Dec 30 '20 at 23:14
  • I will thank you for sharing –  Dec 30 '20 at 23:17
  • 1
    JavaScript's `Date` doesn't have a `.split()` method. – Ivar Dec 30 '20 at 23:17
  • new Date() returns a date string with some information. I am just comparing getting the values there by splitting the string VS using the date functions to get the same values. –  Dec 30 '20 at 23:18
  • sorry i mean date.toString().split(" ")[number] ... –  Dec 30 '20 at 23:20

2 Answers2

1

As the split() method use searching by pattern algorithm and returns an Array which is f(n) = n = O(n) [Big O notation] it is good performance wise.

But Date.prototype.getMonth() involve no searching and return the Number of the month – 1 as it starts counting at 0. (Source : https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/getMonth) f(n) = n = O(1).

Conclusion : Date.getMonth is faster in time and space complexity then .split() method

abnaceur
  • 252
  • 1
  • 2
0

I would use the getMount() method , it's a built in the object so it's more reasonable to me to use it along with all the other methods . When you say "faster" you mean write less code or the code execution is faster?

Arik Jordan Graham
  • 301
  • 1
  • 3
  • 9
  • I mean execution but thank you for your response. I will look at this. –  Dec 30 '20 at 23:13