我很好奇Underscore的_.now
方法为什么比new Date().getTime()
更快。
我在他们的Github代码库中看到了以下内容。
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
请问有人可以解释一下这里发生了什么吗?
我很好奇Underscore的_.now
方法为什么比new Date().getTime()
更快。
我在他们的Github代码库中看到了以下内容。
// A (possibly faster) way to get the current timestamp as an integer.
_.now = Date.now || function() {
return new Date().getTime();
};
其实不必创建一个new Date
对象,可以利用Date.now
提供的优势。唯一的问题是浏览器支持,因此他们包含了一个备用方案。更好的做法可能是直接包含一个polyfill。
if (typeof Date.now != "function")
Date.now = function() { return new Date().getTime(); };
使用这个代替推荐他们自己的帮助函数。
$.each()
而不是一个 Array.prototype.forEach
polyfill。 - Barmar$.each
在任何情况下都无法接近 forEach
的 polyfill :-) - Bergi$.inArray()
是一个更好的例子。 - Barmar通过使用 Date.now,你无需构建一个对象。但它不支持 IE < 9。在这种情况下,它使用旧的 new Date().getTime 函数。
您可以参考此链接了解浏览器支持的详细信息:http://caniuse.com/#search=Date.now
_.now = Date.now || () => +new Date()
。;-) 但我猜不支持Date.now的任何内容都不会支持箭头函数... - RobG