Is parseInt () faster than toString ()?

I am checking if there is an array of pandigital numbers in JavaScript. In short, this means that if it is a 9-digit number, then it should have all the numbers 1-9. I have already sorted an array of numbers, and I have the following loop:

for(var i = 0; i < 9; i++) {
    if(parseInt(digits[i]) != i+1) {
        return false;
    }
}

But I'm just wondering if the following will be faster:

for(var i = 0; i < 9; i++) {
    if(digits[i] != (i+1).toString()) {
        return false;
    }
}

I'm not sure which one will be faster. I feel that converting to a string will be faster than parsing a number. I tried to run several tests, but in fact I did not come up with anything convincing: my computer is old, and the results are everywhere.

Which one will be faster and why? Does this difference in speed increase with large numbers?

EDIT

digits is an array of sorted lines of digits, for example:

var digits = [ "1", "2", "3", "4", "5", "6", "7", "8", "9" ];
+4
2

jsperf.com, parseInt() ( , ).

:

enter image description here

+4

, , , .

, ( ):

for (var i = 0; i < 9; i++) {
    if (digits.charCodeAt(i) != 48 /* '0' */ + i + 1) {
        return false;
    }
}

pandigital:

function pandigital(s) {
    var seen = [0,0,0,0,0,0,0,0,0];
    for (var i = 0; i != s.length; ++i) {
        var ord = s.charCodeAt(i);
        if (ord <= 48 || ord > 48 + s.length) return false;
        if (seen[ord - 48 - 1]++) return false;
    }
    return s.length > 0;
}
+1

Source: https://habr.com/ru/post/1629950/


All Articles