问题
I'm working on a JS to show different messages depending on the current url's hash. Now, that's all working, but I was wondering what the best way would be to access my messages (They'll be coded into a .js file)
At the moment, I have the messages stored in a object like this:
popups = {
TemplateMessage: {
title: "Template Popup Title",
message: "This is a template popup message! Copy this to add a message.",
modal: true
},
AnotherMessage: {
title: "another title",
message: "message.",
modal: true
} /* etc */
};
the way I'm accessing these messages is with a "for in: loop, as follows:
for (key in popups) {
//Do something with...
popups[key].title;
popups[key].message;
popups[key].modal;
}
But would it be more efficient to assign popups[key] to a temporary variable? Like:
var p;
for (key in popups) {
p = popups[key];
//Do something with...
p.title;
p.message;
p.modal;
}
This is all relatively small-scale at the moment and it wouldn't matter a lot (if anything at all) at this stage, but what if you have, say, 25 different objects with 50 properties on each of them? I guess my real question would be, is there a (relatively) significant difference in obtaining a variable from a temp variable, or from a object in a object?
I'm not quite sure how to properly test this, any suggestions?
回答1:
It turns out it is indeed faster to assign your object[key]
to a temporary variable in for-in
loops with large objects, as seen in this jsPerf test. That way, you won't have to obtain object[key]
for every property of the object.
来源:https://stackoverflow.com/questions/13451729/assign-objectkey-to-a-temp-variable-in-a-javascript-for-in-loop