Object identity (equal? vs ==) in Ruby - Performance Comparison
When comparing objects in Ruby, we want to know how fast these checks run as the program grows.
We ask: How does the time to check object equality or identity change with input size?
Analyze the time complexity of the following code snippet.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
puts a.equal?(b) # true
puts a.equal?(c) # false
puts a == c # true
puts a == b # true
This code compares arrays using equal? and == to check identity and equality.
- Primary operation:
equal?checks if two variables point to the same object, which is a simple pointer check. - Primary operation:
==compares contents, which may involve checking each element in the array. - How many times:
equal?runs once per comparison, very fast. - How many times:
==may check each element, so it depends on array size.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations for == |
|---|---|
| 10 | About 10 element checks |
| 100 | About 100 element checks |
| 1000 | About 1000 element checks |
Pattern observation: equal? stays constant time no matter size, but == grows linearly with the number of elements.
Time Complexity: O(1) for equal?, O(n) for ==
equal? is a quick check if two variables are the same object. == takes longer as it compares each element.
[X] Wrong: "equal? and == always take the same time because they both compare objects."
[OK] Correct: equal? just checks if two things are the exact same object, which is very fast. == looks inside objects and compares each part, so it takes longer if the object is bigger.
Understanding how object identity and equality checks work helps you write efficient code and explain your choices clearly in interviews.
"What if we compare nested arrays with ==? How would the time complexity change?"