Why concurrency matters in Ruby - Performance Analysis
When Ruby programs run many tasks at once, concurrency helps manage how fast they finish.
We want to see how running tasks together changes the time it takes compared to running them one by one.
Analyze the time complexity of the following Ruby code using threads.
threads = []
10.times do |i|
threads << Thread.new do
sleep(1) # Simulate work
puts "Task #{i} done"
end
end
threads.each(&:join)
This code runs 10 tasks at the same time using threads, each waiting 1 second before finishing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and running 10 threads that each wait 1 second.
- How many times: 10 times, once per thread.
When tasks run one after another, time adds up. With threads, many tasks run together, so total time can stay close to one task's time.
| Input Size (n) | Approx. Time (seconds) |
|---|---|
| 10 | 10 seconds if sequential, about 1 second with threads |
| 100 | 100 seconds if sequential, about 1 second with threads (if system allows) |
| 1000 | 1000 seconds if sequential, about 1 second with threads (limited by system) |
Pattern observation: Running tasks together can keep total time almost the same, not growing with number of tasks.
Time Complexity: O(1) with concurrency
This means running many tasks at once can keep total time roughly constant, instead of growing with more tasks.
[X] Wrong: "Adding more threads always makes the program faster."
[OK] Correct: Too many threads can slow things down because of overhead and system limits, so speed doesn't always improve.
Understanding how concurrency changes time helps you explain real-world program speed and resource use clearly and confidently.
"What if we changed threads to run tasks one after another? How would the time complexity change?"