Why operators matter in PHP - Performance Analysis
Operators in PHP can affect how fast a program runs, especially when used inside loops or repeated actions.
We want to see how different operators change the work done as input grows.
Analyze the time complexity of the following code snippet.
$sum = 0;
for ($i = 0; $i < $n; $i++) {
$sum += $i * 2;
}
echo $sum;
This code adds twice each number from 0 up to n-1 and sums them all.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplication and addition inside the loop.
- How many times: The loop runs exactly n times.
Each time n grows, the loop runs more times, doing the multiply and add repeatedly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 multiplications and 10 additions |
| 100 | About 100 multiplications and 100 additions |
| 1000 | About 1000 multiplications and 1000 additions |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Multiplying inside the loop makes it slower than adding, so it changes the time complexity."
[OK] Correct: Multiplication is a simple operation done once per loop, so it only changes speed a little, not how time grows with n.
Understanding how operators inside loops affect time helps you explain code efficiency clearly and confidently.
"What if we replaced multiplication with a function call inside the loop? How would the time complexity change?"