On my laptop, snippet 1 takes more than two seconds, whereas snippet 2 takes about 0.05ms. That’s a big difference! But if the variable to test does not host many data, the speed is almost the same.
So, why does the ternary operator become so slow under some circumstances? Why does it depend on the value stored in the tested variable?
The answer is really simple: the ternary operator always copies the value whereas the if statement does not. Why? Because PHP uses a technique known as copy-on-write: When assigning a value to a variable, PHP does not actually create a copy of the content of the variable until it is modified.
via Fabien Potencier – The PHP Ternary Operator: Fast or not?. Huge speed hits using the ternary operator on larger variables. Fortunately it looks like there is already a patch to resolve the problem.