lydiahallie / javascript-questions

A long list of (advanced) JavaScript questions, and their explanations :sparkles:

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

A Question about Number() method

MAMPAgent opened this issue · comments

If we do a little test, we find out:

(function(num) {
    "use strict";
    console.time('minus zero');
    for (let i = 0; i < 10000000; i++) {
        let a = num - 0;
    }
    console.timeEnd('minus zero');


    console.time('Number');
    for (let i = 0; i < 10000000; i++) {
        let a = Number(num);
    }
    console.timeEnd('Number');


    console.time('parseInt');
    for (let i = 0; i < 10000000; i++) {
        let a = parseInt(num, 10);
    }
    console.timeEnd('parseInt');

})('5457885654');

and gives the following result:

minus zero: 1777.696ms
Number: 4624.230ms
parseInt: 4289.564ms

but if we use Number() method:

(function(num) {
    "use strict";
    console.time('minus zero');
    for (let i = 0; i < 10000000; i++) {
        let a = num - 0;
    }
    console.timeEnd('minus zero');


    console.time('Number');
    for (let i = 0; i < 10000000; i++) {
        let a = Number(num);
    }
    console.timeEnd('Number');


    console.time('parseInt');
    for (let i = 0; i < 10000000; i++) {
        let a = parseInt(num, 10);
    }
    console.timeEnd('parseInt');

})('some text');

we get this results:

minus zero: 601.545ms
Number: 3379.065ms
parseInt: 3813.081ms

This demonstrates that the use of Number() is not the fastest method we have here.

Unsure what this relates to, so closing for now.