2
var obj = {};

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

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

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

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?

Paul
  • 26,170
  • 12
  • 85
  • 119
Terry Chen
  • 123
  • 4
  • 15

1 Answers1

3

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.

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