简体   繁体   中英

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. 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.

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

This runs 3x times faster than initial code! 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.

One common way to optimize performance is caching the 'max' value in for loops.

They say accessing length property of array takes some time and should be done once at loop initializer. In our case we call to.getTime() at every loop pass. 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 Browserscope图表

You can see that caching to.getTime() value haven't made any impact for Chrome browser, but looks reasonable for Internet Explorer. I don't know a lot about browser internals, but I think the reason is engine-specific optimizations done automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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