Why arrays are fundamental in Ruby - Performance Analysis
Arrays are one of the most common ways to store lists of items in Ruby.
We want to understand how the time it takes to work with arrays changes as the list gets bigger.
Analyze the time complexity of the following code snippet.
arr = [1, 2, 3, 4, 5]
arr.each do |item|
puts item * 2
end
This code goes through each item in the array and prints double its value.
- Primary operation: Looping through each element of the array.
- How many times: Once for every item in the array.
As the array gets bigger, the time to go through all items grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times printing |
| 100 | 100 times printing |
| 1000 | 1000 times printing |
Pattern observation: Doubling the array size doubles the work needed.
Time Complexity: O(n)
This means the time to complete the task grows directly with the number of items in the array.
[X] Wrong: "Accessing any item in an array takes the same time as going through all items."
[OK] Correct: Accessing one item by its position is very fast and does not depend on array size, but going through all items takes longer as the array grows.
Understanding how array operations grow with size helps you explain your code choices clearly and confidently in interviews.
"What if we changed the array to a hash? How would the time complexity for accessing items change?"