Big O of Objects

Diego Zegarra
3 min readJul 27, 2020

--

I will start off this blog with a brief review of Objects, Big O and for the sake of simplicity, I will just review Constant Time O(1) and Linear Time O(n).

-Objects:
Unordered data structure where everything is stored in key-value pairs.

let instructor = {
firstName: "Princeton",
isInstructor: true,
favoriteNumbers: [1,2,3,4]
}

-Big O Notation:
It’s the way of describing the relationship between the input of a function as it grows and how that changes the runtime of that function, it allows us to talk formally about how the runtime of an algorithm grows as the input grows.

-Constant time O(1):
An algorithm is said to run in constant time if it requires the same amount of time regardless of the input size.
-Linear time O(n):
An algorithm is said to run in linear time if as the input (n) grows, the runtime grows relative to (n).

When to use Objects:
-When you don’t need order.
-When you need fast(constant time) accessing/insertion or removal of data

Big O of Objects:

  • Insertion — O(1)
    No matter how many attributes the object has, JavaScript is able to insert an attribute into an object and will always have roughly the same runtime.
    There is no order so there is no beginning or end of the object so it doesn’t
    matter where you insert because there is no repercussion and the same goes for Removal and Accessing.
  • Removal — O(1)
  • Access — O(1)
    Using a given key, finding the corresponding value.
  • Searching — O(n)
    Searching for a key can still be very fast and be O(1) but if it’s searching for a value then we need to go through every single item and check, so that’s why it is O(n).

Big O of Object Methods:

  • Object.keys — O(n)
    As the number of items in the object grows we would need to visit every key once and add it to the array.
Object.keys(instructor)
=>(3) ["firstName", "isInstructor", "favoriteNumbers"]
  • Object.values — O(n)
    Same as Object.keys but in this case it returns an Array of all the values
Object.values(instructor)
=>(3) ["Princeton", true, Array(4)]
  • Object.entries — O(n)
    Technically it has to do a little more work than Object.key because it has to compile the key AND the value but it just simplifies to O(n).
Object.entries(instructor)
=> (3) [
0: ["firstName", "Princeton"]
1: ["isInstructor", true]
2: ["favoriteNumbers", Array(4)]
]
  • hasOwnProperty — O(1)
    Finds a property in an object without iterating over all the properties
instructor.hasOwnProperty("firstName")
=> true

Conclusion:

Objects are fast!!

--

--