Validate number of days in a given month

前端 未结 13 2111
独厮守ぢ
独厮守ぢ 2021-01-31 18:14

Performance is of the utmost importance on this one guys... This thing needs to be lightning fast!


How would you validate the number of days in a given mont

13条回答
  •  抹茶落季
    2021-01-31 18:47

    In computer terms, new Date() and regular expression solutions are slow! If you want a super-fast (and super-cryptic) one-liner, try this one (assuming m is in Jan=1 format):

    The only real competition for speed is from @GitaarLab, so I have created a head-to-head JSPerf for us to test on: http://jsperf.com/days-in-month-head-to-head/5

    I keep trying different code changes to get the best performance.

    Current version

    After looking at this related question Leap year check using bitwise operators (amazing speed) and discovering what the 25 & 15 magic number represented, I have come up with this optimized hybrid of answers:

    function getDaysInMonth(m, y) {
        return m===2 ? y & 3 || !(y%25) && y & 15 ? 28 : 29 : 30 + (m+(m>>3)&1);
    }
    

    JSFiddle: http://jsfiddle.net/TrueBlueAussie/H89X3/22/

    JSPerf results: http://jsperf.com/days-in-month-head-to-head/5

    For some reason, (m+(m>>3)&1) is more efficient than (5546>>m&1) on almost all browsers.


    It works based on my leap year answer here: javascript to find leap year this answer here Leap year check using bitwise operators (amazing speed) as well as the following binary logic.

    A quick lesson in binary months:

    If you interpret the index of the desired months (Jan = 1) in binary you will notice that months with 31 days either have bit 3 clear and bit 0 set, or bit 3 set and bit 0 clear.

    Jan = 1  = 0001 : 31 days
    Feb = 2  = 0010
    Mar = 3  = 0011 : 31 days
    Apr = 4  = 0100
    May = 5  = 0101 : 31 days
    Jun = 6  = 0110
    Jul = 7  = 0111 : 31 days
    Aug = 8  = 1000 : 31 days
    Sep = 9  = 1001
    Oct = 10 = 1010 : 31 days
    Nov = 11 = 1011
    Dec = 12 = 1100 : 31 days
    

    That means you can shift the value 3 places with >> 3, XOR the bits with the original ^ m and see if the result is 1 or 0 in bit position 0 using & 1. Note: It turns out + is slightly faster than XOR (^) and (m >> 3) + m gives the same result in bit 0.

    JSPerf results: http://jsperf.com/days-in-month-perf-test/6

提交回复
热议问题