Why Ruby has multiple control flow styles - Performance Analysis
We want to understand how Ruby's different ways to control the flow affect how long a program takes to run.
Specifically, we ask: How does choosing one style over another change the number of steps the program does?
Analyze the time complexity of these Ruby control flow examples.
numbers = [1, 2, 3, 4, 5]
# Using if-else
numbers.each do |num|
if num.even?
puts "Even: #{num}"
else
puts "Odd: #{num}"
end
end
# Using case-when
numbers.each do |num|
case num % 2
when 0 then puts "Even: #{num}"
else puts "Odd: #{num}"
end
end
This code checks each number and prints if it is even or odd using two different control flow styles.
Look at what repeats in the code.
- Primary operation: Looping through each number in the list.
- How many times: Once for each number (5 times here, but could be more).
The if-else and case-when checks happen inside the loop, but only once per number.
As the list gets bigger, the program does more checks.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Each new number adds one more check, so the work grows steadily as the list grows.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Using case-when is slower than if-else because it looks more complex."
[OK] Correct: Both check each item once, so they take about the same time. The style choice doesn't change how many steps happen.
Understanding how different ways to write code affect speed helps you write clear and efficient programs. It shows you can think about both style and performance.
"What if we replaced the array with a nested array and checked each inner number? How would the time complexity change?"