13

主な違いは何ですか:

dt = new Date();
ms = Date.parse(dt);

dt = new Date();
ms = dt.getTime();

出力は同じですが、違いは何ですか?どちらを使用すればよいですか?

4

4 に答える 4

1

Performance would be the big difference. In the both cases, you allocate a Date instance. In the first example, you pass the date instance into parse() which expects a String. The JavaScript engine will call toString() on the Date which will also allocate a String for the date. Basically, it is the same as:

dt = new Date();             // allocate a Date
dateString = dt.toString();  // allocate a String
ms = Date.parse(dateString); // Total: 2 allocations

In the second example, you are calling the getTime() method on the Date instance which will eliminate the String allocation.

dt = new Date();             // allocate a Date
ms = dt.getTime();           // Total: 1 allocation

Another option to eliminate all allocations would be to call Date.now():

ms = Date.now();             // Total: 0 allocations

This directly returns the time in ms without constructing the other objects.

于 2013-09-21T19:13:59.363 に答える