+new Date() - Is this good practice?

前端 未结 5 1226
一整个雨季
一整个雨季 2020-12-12 22:37

So we had the Discussion today in our company about +new Date() being good practice or not. Some prefer this way over new Date().getTime().

5条回答
  •  天命终不由人
    2020-12-12 23:07

    I find that this type of code tends to often be called infrequently, so I thought it best to add tests for the inline usage you typically see:

    e.g.

    var t = (new Date()).getTime();
    

    and

    var t = +new Date();
    

    The JSPerf results show these two are not much different in speed: http://jsperf.com/get-time-vs-unary-plus/7

    enter image description here

    The problem with the previous perf results are that the example is not practical. You would not keep getting the same now in practice. You would just store the getTime() result once if the now was not changing. As these new results show, the speed difference is not significant in the typical usage situation.

    So I guess the general advice is, use either for one-off usage +new Date() being shorter, but (new Date()).getTime() is more readable (and a tad faster).

    Date.now():

    If you are going to use the newer Date.now(), you will want to implement the recommended shim to support older browsers from here

    if (!Date.now) {
      Date.now = function now() {
        return new Date().getTime();
      };
    }
    

    (Although I am puzzled why they don't just use an anonymous function in that example)

提交回复
热议问题