简体   繁体   English

JavaScript:遍历日期

[英]JavaScript: Iterating over dates

In some application I need to produce an array of dates within specified range. 在某些应用程序中,我需要产生指定范围内的日期数组。 There was a major performance issue with initial approach: 初始方法存在一个主要的性能问题:

var from = new Date("2016-01-01");
var to = new Date("2016-12-31");

for (var current = new Date(from); current <= to; current.setDate(current.getDate() + 1);

The primary point is that Date is a complex object and it's comparison takes significant time. 要点是Date是一个复杂的对象,它的比较需要花费大量时间。 It's better to call getTime() to get elementary number value and compare it, as method call overhead is less than time required for comparison operation. 最好调用getTime()来获取基本数字值并进行比较,因为方法调用的开销小于比较操作所需的时间。

for (
  var current = new Date(from);
  current.getTime() <= to.getTime();
  current.setDate(current.getDate() + 1)
);

This runs 3x times faster than initial code! 这个运行的比最初的代码快3个倍! But let's see what else can be done here. 但是,让我们看看这里还有什么可以做的。

Some general suggestions on performance considerations are made for Javascript optimizations for Internet Explorer question. 针对Internet Explorer问题的Javascript优化,提出了一些有关性能注意事项的一般建议。

One common way to optimize performance is caching the 'max' value in for loops. 优化性能的一种常用方法是在for循环中缓存“ max”值。

They say accessing length property of array takes some time and should be done once at loop initializer. 他们说访问数组的length属性需要一些时间,应该在循环初始化程序中进行一次。 In our case we call to.getTime() at every loop pass. 在我们的例子中,我们在每次循环传递时都调用to.getTime() I'm not absolutely sure, but guess it's more time-consuming operation than accessing object attribute. 我不太确定,但是我猜它比访问对象属性更耗时。

for (
  var current = new Date(from), toTime = to.getTime();
  current.getTime() <= toTime;
  current.setDate(current.getDate() + 1)
);

Here's a chart from jsPerf test : 这是jsPerf测试的图表:

jsPerf Browserscope图表

You can see that caching to.getTime() value haven't made any impact for Chrome browser, but looks reasonable for Internet Explorer. 您可以看到,缓存to.getTime()值对Chrome浏览器没有任何影响,但是对于Internet Explorer来说似乎是合理的。 I don't know a lot about browser internals, but I think the reason is engine-specific optimizations done automatically. 我对浏览器的内部了解不多,但是我认为原因是引擎特定的优化是自动完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM