主な違いは何ですか:
dt = new Date();
ms = Date.parse(dt);
と
dt = new Date();
ms = dt.getTime();
出力は同じですが、違いは何ですか?どちらを使用すればよいですか?
主な違いは何ですか:
dt = new Date();
ms = Date.parse(dt);
と
dt = new Date();
ms = dt.getTime();
出力は同じですが、違いは何ですか?どちらを使用すればよいですか?
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.