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]