mercredi 24 juin 2015

JavaScript ternary vs if / else micro-benchmark

I was trying to figure out the most efficient way to create a checkerboard pattern in JavaScript and did some ternary vs if / else micro-benchmarking. I was under the assumption before starting that the results would be the same but it appears that if / else is almost always a little faster than ternary (occasionally ternary's best result is better than if / else)

I did my testing in Firefox (38.0.5 if it matters) with several different iterations counts of numLog, i, and j. Below I have results just where numLog iterates to 3, i to 15000, and j to 15000. These numbers are somewhat arbitrary but are small enough that browser does not ask me to stop the script yet large enough that I feel the results are consistent

Ternary Results:

for (var numLog = 0; numLog < 3; numLog++) {
    var start = new Date().getTime();
    for (var i = 0; i < 15000; i++) {
        var iAND = i&1;
        for (var j = 0; j < 15000; j++) {
            var jAND = j&1;
            var foo = (!iAND && jAND) || (iAND && !jAND) ? "#202020" : "#e0e0e0";
        }
    }
    console.log(new Date().getTime()-start);
}
// Example results: 1635, 1582, 1592

If / Else Results:

for (var numLog = 0; numLog < 3; numLog++) {
    var start = new Date().getTime();
    for (var i = 0; i < 15000; i++) {
        var iAND = i&1;
        for (var j = 0; j < 15000; j++) {
            var jAND = j&1;
            var foo;
            if ( (!iAND && jAND) || (iAND && !jAND) )
                foo = "#202020";
            else
                foo = "#e0e0e0";
        }
    }
    console.log(new Date().getTime()-start);
}
// Example results: 1549, 1555, 1597

Is there some reason that ternary seems to always be slightly more efficient?

Aucun commentaire:

Enregistrer un commentaire