Michael Payne Michael Payne - 2 months ago 25
Javascript Question

Will JS object literals defined in a function be optimized?

Will JavaScript optimize an object literal defined in a method? Suppose I have a simple lookup function that gets used extensively:

function lookup(value) {
return {
"A": "a",
"B": "b",
"C": "c"
}[value];
}


Is there any benefit to defining the object outside of the function for reuse, or will the engine optimize that away for me?

Answer

var object = {
	"A": "a",
	"B": "b",
	"C": "c"
};

function lookup1(value) {
    return object[value];
}

function lookup2(value) {
    return {
		"A": "a",
		"B": "b",
		"C": "c"
	}[value];
}

var dateBefore = new Date().getTime();
for (var i = 0; i < 100000000; i++) {
	var a = lookup2('A');
}
var dateAfter = new Date().getTime();

console.log(dateAfter - dateBefore);

var dateBefore = new Date().getTime();
for (var i = 0; i < 100000000; i++) {
	var a = lookup1('A');
}
var dateAfter = new Date().getTime();

console.log(dateAfter - dateBefore);

Comments