When not to use Moment JS?
There is a very cool stuff around called Moment JS. It makes dealing with Dates in javascript a lot easier, e.g parsing date strings, manipulating date objects or localizing dates and date ranges.
However, sometimes it is just better to stuck to the plain old javascript version, especially if speed really matters. What do I mean?
I am building a small app using Meteor JS, where I have to loop over a lot of elements and assign a date string to each element created from a javascript Date object.
The easiest way to do it would be moment.js. However, after doing a little profiling it turns out, that using plain javascript is much faster.
Let's assume that we have a test_data array with 10.000 elements, and that moment.js is available.
Using Moment.js (~117 ms)
a.forEach(function(){ var date_string = moment().format('YYYY-MM-DD'); });
Using plain Javascript (~15 ms)
a.forEach(function(){ var today = new Date(); var date_string = today.getFullYear() + '-' + (today.getMonth()+1) + '-' + today.getDay(); });
There is something however, that I did not mention yet. By using moment.js you will get a nicely formatted date string, like 2015-01-01. Using the pure Javascript solution you would get 2015-1-1, which is not as cool at all. If you need the padding zeros for the month and the date, you can definetely do something, but it will slow down your script to the same speed as moment.js.
Padding month and date with zeros (~100 ms)
Number.prototype.padLeft = function (n,str){ return Array(n-String(this).length+1).join(str||'0')+this; } //Now you can call it on any number: var today = new Date(); var month = (today.getMonth()+1).padLeft(2); //returns '02'
Conclusion: I really like Moment.js, I use it whereever i can, but if you really need speed (rendering, etc.), and formatting is not must, then think over if you can do the job with pure javascript.














