本文介绍了JavaScript访问对象属性的运行时复杂度O(?)是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var obj = {};

obj["A"] = true;
obj["B"] = true;
obj["C"] = true;

console.log(obj["D"]);

上面的代码将打印"undefined".当javascript试图访问obj ["D"]时,运行时复杂度是多少?我想它将与尝试访问obj ["A"]一样?

The above code will print "undefined". What is the runtime complexity when javascript is trying to access obj["D"] ? I guess it will be the same as it is trying to access obj["A"]?

之所以这样问,是因为我正在比较这两个代码之间的效率:

The reason why I am asking this is because I am comparing the efficiency between these two code:

//Code 1
var x = ["a","b","c"];
var y = ["a","b","c"];

for(i = 0; i<x.length; i++){
    for(j = 0; j<y.length; j++){
        console.log(i==j);
    }
}

//Code2
var _x = {};
var _y = ["a", "b", "c"];

_x["a"] = true;
_x["b"] = true;
_x["c"] = true;

for(i = 0; i<_y.length; i++){
    if(_x[_y[i]] != undefined){
        console.log("something");
    }
}

我想知道在运行时复杂度方面哪个效率更高.我想如果访问一个对象属性需要O(n),那么两个代码的运行时间将是相同的吗?

I would like to know which one is more efficient in term of runtime complexity.I suppose if accessing an object property takes O(n), then the runtime of the two code would be the same?

推荐答案

JavaScript语言对操作的时间复杂度没有任何要求,因此性能将取决于您使用的JavaScript解释器.

The Javascript language doesn't set any requirements on the time complexity of operations, so performance will depend on the Javascript interpreter you're using.

(在某些情况下,它甚至可能不是固定的;大多数现代Javascript解释器会执行运行时优化,这可能会更改操作的时间复杂性.)

(In some cases, it may not even be fixed; most modern Javascript interpreters perform runtime optimizations which may change the time complexity of operations.)

这篇关于JavaScript访问对象属性的运行时复杂度O(?)是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 14:26