将对象[key]分配给javascript中的temp变量“for ... in”环? [英] Assign object[key] to a temp variable in a javascript "for...in" loop?

查看:160
本文介绍了将对象[key]分配给javascript中的temp变量“for ... in”环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究JS以根据当前url的哈希显示不同的消息。
现在,这一切都有效,但我想知道访问我的消息的最佳方法是什么(它们将被编码成.js文件)

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 */
};

我访问这些消息的方式是for in:loop,如下:

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;
}

但是将弹出窗口[key]分配给临时变量会更有效吗?
赞:

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;
}

这个目前都是规模相对较小的,在这个阶段并没有多大关系(如果有的话),但是如果你有25个不同的对象,每个对象有50个属性呢?
我想我真正的问题是,从临时变量或对象中的对象获取变量是否存在(相对)显着差异?

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?

推荐答案

事实证明它确实是更快地将对象[key] 分配给带有大对象的 for-in 循环中的临时变量,如此jsPerf测试。这样,您就不必为对象的每个属性获取 object [key]

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.

这篇关于将对象[key]分配给javascript中的temp变量“for ... in”环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆