Assigning a date from a String

Benchmark created by Blazedd on


Description

Tests if passing a date as a string vs parsing the string via regex might grant better performance

Setup

var timestamp = '2000/01/01 00:00:00',
        dates = [],
        total = 1000,
        i = 0,
        pattern = new RegExp('([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2})\.([0-9]{1,2})');
    
    var makeNiceDate = function(date, len){
        len = len || 2;
        return String("0"+date).slice(-len);
    }
    while(i < total){
        var d = new Date(timestamp);
        d.setDate(i);
        dates.push("" + makeNiceDate(d.getFullYear(), 4) + "-" + makeNiceDate(d.getMonth()+1) + "-" + makeNiceDate(d.getDate()) + " " + makeNiceDate(d.getHours()) + ":" + makeNiceDate(d.getMinutes()) + "." + makeNiceDate(d.getSeconds()));
        i++;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
Automatic Parse
for (var i = dates.length - 1; i >= 0; i--) {
        new Date(dates[i]);
}
ready
Regex Parse
for (var i = dates.length - 1; i >= 0; i--) {
     var parts = dates[i].match(pattern);
     new Date(parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]);
}
ready
Slice Parse
for (var i = dates.length - 1; i >= 0; i--) {
     new Date(dates[i].slice(0, 4), dates[i].slice(5, 7), dates[i].slice(8, 10), dates[i].slice(11, 13), dates[i].slice(14, 16), dates[i].slice(17, 19));
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Blazedd on