What's faster in JS: Object with keys or array with an if statement?

Viewed 199

Which of these structures is generally more performant in JS with the v8 engine?

Example 1:

const obj = {
  a: 'hello',
  b: 'world',
  c: 'etc',
};

function getVal(str) {
  return obj[str];
}

getVal('b');

Example 2:


function getVal(str) {
  if(str=='a') return 'hello';
  if(str=='b') return 'world';
  return 'etc';
}

getVal('b');

I would imagine example 2 is faster, but 1 is better code. I ask because I'm looking at chess AI, and can structure the position weights as objects:

const positions_w = {
    'p':[
            [ 100, 100, 100, 100, 105, 100, 100,  100],
            [  78,  83,  86,  73, 102,  82,  85,  90],
            [   7,  29,  21,  44,  40,  31,  44,   7],
            [ -17,  16,  -2,  15,  14,   0,  15, -13],
            [ -26,   3,  10,   9,   6,   1,   0, -23],
            [ -22,   9,   5, -11, -10,  -2,   3, -19],
            [ -31,   8,  -7, -37, -36, -14,   3, -31],
            [   0,   0,   0,   0,   0,   0,   0,   0]
        ],
    'n': // ...

and then get them with positions_w[piece.type][y][x] or structure them in arrays:

const p = [
            [ 100, 100, 100, 100, 105, 100, 100,  100],
            [  78,  83,  86,  73, 102,  82,  85,  90],
            [   7,  29,  21,  44,  40,  31,  44,   7],
            [ -17,  16,  -2,  15,  14,   0,  15, -13],
            [ -26,   3,  10,   9,   6,   1,   0, -23],
            [ -22,   9,   5, -11, -10,  -2,   3, -19],
            [ -31,   8,  -7, -37, -36, -14,   3, -31],
            [   0,   0,   0,   0,   0,   0,   0,   0]
        ];

and then get them with if(piece.type=='p')return p[y][x]

1 Answers

If the object is small and was created with all of its keys, the speed of property access should be comparable to a switch statement.

One thing to consider however is that you will be updating your position weights pretty often. For this reason I think one big "3D" Int16Array would make a greater difference overall.

In any case, I would make sure no part of my app is dependant on the concrete data structure so that it is possible to delay this decision until later when you can actually profile your AI speed.

Related