Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

creating a calendar in javascript

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...