Day of week from string date

JavaScript performance comparison

Test case created by dany28

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var date = '2020-03-11';
  var dayNames = ['sunday','monday','tuesday','wednesday','thursday','friday','saturday'];
  function firstDayOfYearCache(year) {
    switch (year) {
      case 2020:
        return 3;
    }
    const YY = (year - 1) % 100;
  
    const C = year - 1 - YY;
    const G = YY + Math.round(YY / 4);
    return (((C / 100) % 4) * 5 + G) % 7;
  }
  function firstDayOfYear(year) {
    const YY = (year - 1) % 100;
    const C = year - 1 - YY;
    const G = YY + Math.round(YY / 4);
    return (((C / 100) % 4) * 5 + G) % 7;
  }
  function isLeapYear(year) {
    switch (year) {
      case 2018:
      case 2019:
      case 2021:
      case 2022:
      case 2023:
      case 2025:
      case 2026:
      case 2027:
        return 0;
      case 2020:
      case 2024:
      case 2028:
        return 1;
  
      default:
        return (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) ? 1 : 0;
    }
    
  }
  function dayOfYear(year, month, day) {
    switch (month) {
      case 1:
        return day;
      case 2:
        return 31 + day;
      case 3:
        return 59 + day + isLeapYear(year);
      case 4:
        return 90 + day + isLeapYear(year);
      case 5:
        return 120 + day + isLeapYear(year);
      case 6:
        return 151 + day + isLeapYear(year);
      case 7:
        return 181 + day + isLeapYear(year);
      case 8:
        return 212 + day + isLeapYear(year);
      case 9:
        return 243 + day + isLeapYear(year);
      case 10:
        return 273 + day + isLeapYear(year);
      case 11:
        return 304 + day + isLeapYear(year);
      case 12:
        return 334 + day + isLeapYear(year);
    }
    return day;
  }
  function dayOfWeek(year, month, day) {
    return (firstDayOfYearCache(year) + dayOfYear(year, month, day) - 1) % 7;
  }
  function getYear(date) {
    return ((+date[0] * 10 + +date[1]) * 10 + +date[2]) * 10 + +date[3];
  }
  function getMonth(date) {
    return +date[5] * 10 + +date[6];
  }
  function getDate(date) {
    return +date[8] * 10 + +date[9];
  }

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
Date() && getDay()
var dt = new Date(date);
return dayNames[dt.getDay()];
pending…
dayOfWeek +slice
return dayNames[dayOfWeek(+date.slice(0, 4), +date.slice(5, 7), +date.slice(8, 10))];
pending…
dayOfWeek convert manual
return dayNames[dayOfWeek(getYear(date), getMonth(date), getDate(date))];
pending…

Revisions

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

0 Comments