Javascript 性能 - Date.now() 与 Date.getTime()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12517359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Performance - Date.now() vs Date.getTime()
提问by
var timeInMs = Date.now();
per MDN
每个MDN
vs.
对比
var timeInMs = new Date(optional).getTime();
per MDN.
每个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?
除了语法和在第二个版本中通过 optional 设置日期(不是当前)的能力之外,两者之间有什么区别吗?
Date.now() is faster - check out the jsperf
Date.now() 更快 - 查看jsperf
回答by Pointy
These things are the same (editsemantically; performance is a little better with .now()
):
这些东西是相同的(在语义上编辑;使用 性能稍好一些.now()
):
var t1 = Date.now();
var t2 = new Date().getTime();
However, the time value from any already-created Date
instance is frozen at the time of its construction (or at whatever time/date it's been set to). That is, if you do this:
但是,任何已创建Date
实例的时间值在其构建时(或在其设置的任何时间/日期)都会被冻结。也就是说,如果你这样做:
var now = new Date();
and then wait a while, a subsequent call to now.getTime()
will tell the time at the point the variable was set.
然后稍等片刻,随后的调用now.getTime()
将告诉设置变量时的时间。
回答by jrajav
They are effectively equivalent, but you should use Date.now()
. It's clearer and about twice as fast.
它们实际上是等效的,但您应该使用Date.now()
. 它更清晰,速度快两倍。
Edit: Source: http://jsperf.com/date-now-vs-new-date
回答by Gregory Magarshak
When you do (new Date()).getTime()
you are creating a new Date object. If you do this repeatedly, it will be about 2x slower than Date.now()
当您这样做时,(new Date()).getTime()
您正在创建一个新的 Date 对象。如果重复执行此操作,它将比 Date.now() 慢约 2 倍
The same principle should apply for Array.prototype.slice.call(arguments, 0)
vs [].slice.call(arguments, 0)
同样的原则应该适用于Array.prototype.slice.call(arguments, 0)
vs[].slice.call(arguments, 0)
回答by SashaK
Sometimes it's preferable to keep some time tracking variable in a Date object format rather than as just a number of milliseconds, to have access to Date's methods without re-instantiating. In that case, Date.now() still wins over new Date() or the like, though only by about 20% on my Chrome and by a tiny amount on IE.
有时最好在 Date 对象格式中保留一些时间跟踪变量,而不是仅仅保留几毫秒,以便无需重新实例化即可访问 Date 的方法。在这种情况下,Date.now() 仍然胜过 new Date() 等,尽管在我的 Chrome 上只有大约 20%,而在 IE 上只有很小的一部分。
See my JSPERF on
请参阅我的 JSPERF
timeStamp2.setTime(Date.now()); // set to current;
vs.
对比
timeStamp1 = new Date(); // set to current;
回答by Brett Zamir
Yes, that is correct; they are effectively equivalent when using the current time.
对,那是正确的; 当使用当前时间时,它们实际上是等效的。