What is the time complexity to check if a key exists in an object using in
property:
Example:
var obj = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
...
}
if("key1" in obj)
What is the time complexity to check if a key exists in an object using in
property:
Example:
var obj = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
...
}
if("key1" in obj)
This is from the V8 Design docs
Most JavaScript engines use a dictionary-like data structure as storage for object properties - each property access requires a dynamic lookup to resolve the property's location in memory. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk. In these languages, instance variables are located at fixed offsets determined by the compiler due to the fixed object layout defined by the object's class. Access is simply a matter of a memory load or store, often requiring only a single instruction.
To reduce the time required to access JavaScript properties, V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes. [...] In V8, an object changes its hidden class when a new property is added.
so basically it would be O(1) in time complexity to check for a key in an object even if the JavaScript engines use a dictionary-like data structure because on average accessing a key in a dictionary would be O(1).