Question

If I am going to be using Date() to generate dates and use its methods in my script should I create a Date() object once and re-use it or just create a new instance each time?

Is it more efficient\faster to do this:

var1 = new Date(2014, 5, 3)
var2 = new Date(2013, 2, 30)
var3 = new Date(2015, 10, 2)

or this:

myDate = new Date()

myDate.setDate(3)
myDate.setMonth(5)
myDate.setYear(2014)
var1 = myDate

myDate.setDate(30)
myDate.setMonth(2)
myDate.setYear(2013)
var2 = myDate

myDate.setDate(2)
myDate.setMonth(10)
myDate.setYear(2015)
var3 = myDate

Edit: my question wasn't very clear, let me try to explain:

I'm only using the Date() object for its methods and generating dates- meaning I don't really need a bunch of Date() objects just one I can use to do one-off operations like generate some date and call a method like toJSON() or something on it. After I generate the date and call the method I don't need a persistent object hanging around because I won't be doing anything with it. Would it consume less resources to reuse one Date() object like this or is it even slower?

Another edit: I was thinking I could also put it in a function so I'd be doing this:

myDate = new Date();
setDate = function(dateObj,day,month,year) {
    dateObj.setDate(dat);
    dateObj.setMonth(month);
    dateObj.setYear(year);
    return myDate;
}

var1 = setDate(myDate,12,10,2014);

Anything value in doing it like this?

Était-ce utile?

La solution

Your examples are two different things. The first example creates three separate Date objects, which can have three different dates.

The second example creates one Date object, which var1, var2, and var3 point to. When you change the Date object, var1, var2, and var3 will all see that change.

Autres conseils

new Date is a constructor. it is written in javascript. In OO programming you usually don't replicate code. So if you have a constructor new Date() - which you have in JS, and setters, it is most likely that doing new Date(2013, 2, 30) is equivalent to:

var myDate = new Date();
myDate.setDate(30);
myDate.setMonth(2);
myDate.setYear(2013);

according to this, the allocation alone will cost you and the second way you presented is faster. BUT (!!!) the two ways don't give the same results. In the first you gain three different objects. in the later you get only one.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top