Search code examples
javascriptarraysperformancev8

Why is if(1) faster than if(true)


I'm trying to make Conway's game of life in JavaScript and canvas, I have a matrix of 1280x720 that I use to store cells data, I'm currently storing the data as 1 = alive, 0 = dead, and then when I check if a cell is alive or not I simply do: if(matrix[i][j]) I was curious if this could be improved and did some tests at https://jsbench.me/ replicating a similar scenario and noticed that if using "true/false", the whole thing is +-11% slower, why is it the case? Shouldn't it be faster?

Example benchmark, just change 1 to true to test the other scenario

let array = []
for(let i = 0; i<1000000; i++){
   array.push(1)
}
let sum = 0
for(let i = 0; i<1000000;i++){
    if(array[i]){
        sum++
    }
}

Solution

  • The performance difference you see isn't strictly due to the if statement evaluation, it's due to the array element kind that the value (1 or true) is accessed from. The V8 engine distinguishes between arrays of different element kinds. An array of 1 will be treated as PACKED_SMI_ELEMENTS, while an array of true will be treated as PACKED_ELEMENTS. Because of that, the version using boolean elements will be a little bit slower.

    As an illustration, here's the lattice of relative performance optimizations applied between array element kinds, with best performance at the top left, and worst performance at the bottom right:

    element kinds lattice

    And here's a benchmark comparing both your tests to one I added based on my comment below:

    benchmark results