Difference between Date.parse() and .getTime()

前端 未结 4 880
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 11:33

What\'s the main difference between:

dt = new Date();
ms = Date.parse(dt);

and

dt = new Date();
ms = dt.getTime();
<         


        
4条回答
  •  不知归路
    2021-01-04 12:07

    Performance would be the big difference. In the both cases, you allocate a Date instance. In the first example, you pass the date instance into parse() which expects a String. The JavaScript engine will call toString() on the Date which will also allocate a String for the date. Basically, it is the same as:

    dt = new Date();             // allocate a Date
    dateString = dt.toString();  // allocate a String
    ms = Date.parse(dateString); // Total: 2 allocations
    

    In the second example, you are calling the getTime() method on the Date instance which will eliminate the String allocation.

    dt = new Date();             // allocate a Date
    ms = dt.getTime();           // Total: 1 allocation
    

    Another option to eliminate all allocations would be to call Date.now():

    ms = Date.now();             // Total: 0 allocations
    

    This directly returns the time in ms without constructing the other objects.

提交回复
热议问题