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?

3
  • Oh, you meant "run time" or "execution time" rather than "runtime" (as per this answer stackoverflow.com/questions/3900549/what-is-runtime ) ... Commented Jan 29, 2015 at 21:35
  • Sorry, i ment "runtime" Commented Jan 29, 2015 at 21:38
  • 1
    runtime complexity, in BigO Commented Jan 29, 2015 at 21:39

1 Answer 1

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.)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.