设置函数变量与使用对象文字相同

Is setting function variables the same as using an object literal

本文关键字:对象 文字 函数 变量 设置      更新时间:2023-09-26

就性能和创建的数据结构而言,是:

function coords(xpos, ypos, zpos){
    this.xpos = xpos;
    this.ypos = ypos;
    this.zpos = zpos;
    return this;
}
var coordinates = coords(0, 0, 0); // notice I am not calling new

同:

function coords(xpos, ypos, zpos){
    return {
        xpos : xpos,
        ypos : ypos,
        zpos : zpos, 
    };
}
var coordinates = coords(0, 0, 0);

假设我有很多coordinates,是否有更高性能的生成方法。

  1. 第二个示例使用对象文字,而不是JSON
  2. 在语义方面:两者在语义上并不等价即使在第一个示例中将+ s更改为= s,coordinates也是undefined,因为您没有使用new,并且coords不会返回任何内容
  3. 就性能而言:这是微观优化中的微观est。停止思考,继续解决真正的问题
  4. 如果您仍然关心性能差异(您不应该),请编写一个jsPerf基准测试

正如SJFrK所评论的,

最快的方法是根本不使用一个函数,例如

var coordinates = { xpos: 0, ypos: 0, zpos: 0 };

第一个片段应该是这样的:

function coords(xpos, ypos, zpos) {
    this.xpos = xpos;
    this.ypos = ypos;
    this.zpos = zpos;
}
var coordinates = new coords(0, 0, 0);

也就是说,你的选择将取决于你想对结果做什么(你想有一个对象文字还是一个可以定义原型的对象),但对于任何合理的使用来说,性能都是一样的。

在创建对象的第一种方法中,必须使用

CCD_ 8和在javascript中使用CCD_。在第二种方法中,执行函数将返回一个坐标对象。

我更喜欢第二种方法,尽管它在现代浏览器中没有太大区别。

这是一个简单的基准http://jsperf.com/objecr-vs-fn-perf-test

在Firefox 7中,第一种方法比第二种慢75%,在chrome 17中,慢30%

在第一个示例中,coordinates是未定义的。函数没有返回任何内容。您需要在第一个示例中使用new,以便它与第二个示例相同。(还有一个打字错误,+应该是=

function coords(xpos, ypos, zpos){
    this.xpos = xpos;
    this.ypos = ypos;
    this.zpos = zpos;
}
var coordinates = new coords(0, 0, 0);

在第二个示例中,您没有使用JSON。你只是在使用obect文字。JSON是一种将对象/数组表示为字符串的方法。

至于性能,第二个可能会更快,但这不是你应该担心的。