Performance - Date.now() vs Date.getTime()

var timeInMs = Date.now();

per MDN

vs.

var timeInMs = new Date(optional).getTime();

per MDN.

Is there any difference between the two, besides the syntax and the ability to set the Date (to not the current) via optional in the second version?

Date.now() is faster - check out the jsperf

111484 次浏览

是的,这是正确的; 当使用当前时间时,它们实际上是等价的。

这些事情是相同的(编辑语义; 使用 .now()性能稍微好一点) :

var t1 = Date.now();
var t2 = new Date().getTime();

但是,来自任何已经创建的 Date实例的时间值在其构造时(或在其设置为的任何时间/日期)被冻结。也就是说,如果你这样做:

var now = new Date();

然后等待一段时间,随后对 now.getTime()的调用将告诉设置变量的时间点。

它们实际上是等效的,但是你应该使用 Date.now(),它更清晰,速度大约是 Date.now()的两倍。

编辑: 来源: http://jsperf.com/date-now-vs-new-date

执行 (new Date()).getTime()时,将创建一个新的 Date 对象。如果重复执行此操作,它将比 Date. now ()慢大约2倍

同样的原则也适用于 Array.prototype.slice.call(arguments, 0)[].slice.call(arguments, 0)

有时,最好将一些时间跟踪变量保持为 Date 对象格式,而不仅仅是几毫秒,这样就可以访问 Date 的方法而不必重新实例化。在这种情况下,Date.now ()仍然胜过 new Date ()或类似的东西,尽管在我的 Chrome 浏览器上只赢了大约20% ,在 IE 浏览器上只赢了一小部分。

看看我的 JSPERF

timeStamp2.setTime(Date.now()); // set to current;

对。

timeStamp1 = new Date(); // set to current;

Http://jsperf.com/new-date-vs-settime

Date.now()正在调用类 Date的静态方法 now()new Date().getTime()可分为两个步骤:

  1. new Date(): 调用 Date类的 constructor()方法来初始化 Date类的一个实例。
  2. 调用我们刚刚初始化的实例的 getTime()方法。

MDN web docs Date.now()分类为 Date的静态方法,将 Date.prototype.getTime()分类为实例方法。

我试图为你的问题找到精确的答案。我找到了一个带有 基准的页面,非常清楚。

静态 约会,现在()方法返回自 1970年1月1日世界协调时00:00:00以来经过的毫秒数。

GetTime ()方法返回自 ECMAScript 时代以来的毫秒数。 可以使用此方法帮助将日期和时间分配给另一个 Date 对象。此方法在功能上等效于 ValueOf ()方法。

资料来源: https://developer.mozilla.org/

例如:

const moonLanding = new Date('July 20, 69 20:17:40 GMT+00:00');


console.log('getTime:::', moonLanding.getTime()); // expected output: -14182940000
console.log('valueOf:::', moonLanding.valueOf()); // expected output: -14182940000