Performance Tests
Visit jackgiffin.com for performance tests
The Code
Well, for one thing I would write all of the HTML at once. Another thing is that I would use insertAdjacentHTML so that current event listeners and other virtual parts of the body's current content don't get taken off. So, using this and several other micro-optimizations, I tripled the performance of your code (in chrome, at least). The following optimized function preserve most of your functions original functionality.
let currentRound = -1;
MakeDateRange = function( beginText, endText, __func ){
'use-strict';
const t = performance.now();
let begin = new Date(beginText), end = new Date(endText),
curRound = 'z' + ++currentRound,
len = ((end.getTime()-begin.getTime())/86400000)|0,
i = -1,
bodyHTML = '',
dates;
if (__func instanceof Function){
while (i++ !== len)
begin.setDate(begin.getDate()+1), bodyHTML += __func(begin, curRound);
document.body.insertAdjacentHTML('beforeend',bodyHTML);
perfs[1] = (performance.now()-t );
return document.getElementsByName(curRound);
}
dates = new Array(len);
while (i++ !== len)
begin.setDate(begin.getDate()+1), dates[len] = new Date(begin);
perfs[1] = (performance.now()-t );
return dates;
};
dates = MakeDateRange(
"2015 2 1 0:0:0 GMT+0100",
"2016 2 1 0:0:0 GMT+0100" ,
function(date, curRound){ return '<div name='+curRound+'>'+date+'</div>' }
);
console.log(dates);
However, if you inline __func then it will be even faster:
let currentRound = -1;
MakeDateRange = function( beginText, endText ){
'use-strict';
const t = performance.now();
let begin = new Date(beginText), end = new Date(endText),
curRound = 'z' + ++currentRound,
template = '<div name="' + curRound + '">',
len = ((end.getTime()-begin.getTime())/86400000)|0,
i = -1,
bodyHTML = '',
dates;
while (++i !== len)
begin.setDate(begin.getDate()+1), bodyHTML += template + begin + '</div>';
document.body.insertAdjacentHTML('beforeend',bodyHTML);
perfs[2] = (performance.now()-t );
return document.getElementsByName(curRound);
};
dates = MakeDateRange(
"2015 2 1 0:0:0 GMT+0100",
"2016 2 1 0:0:0 GMT+0100"
);
console.log(dates);
And also, I would highly recommend using let and const instead of var because performance.now has been available since IE10, and let and const are available since IE11. IE10 is only obtainable through having specific windows 7 updates. And, most windows users have either no updates installed which would mean IE9, or, much more commonly, all windows updates installed which would mean IE11. It is unlikely any windows 7 user with just the right updates for IE10 will visit your site, so you might as well shoot for IE11.