Is ternary operator faster than if in php?

The PHP Ternary Operator: Fast or not?

July 16, 2011

People like micro-optimizations. They are easy to understand, easy to apply... and useless. But some time ago, while reviewing pull requests for Twig, I read an interesting discussion about the performance of the ternary operator in PHP (thanks to @nikic for the investigation).

Do you know which following snippet is the fastest (of course, they do exactly the same)?

// snippet 1
$tmp = isset($context['test']) ? $context['test'] : '';

// snippet 2
if (isset($context['test'])) {
    $tmp = $context['test'];
} else {
    $tmp = '';
}

The right answer is: it depends. Most of the time, they are about the same speed and you don't need to care. But if $context['test'] contains a large amount of data, snippet 2 is much faster than snippet 1.

Here is the code I have used to test different scenarii:

$context = array('test' => true);

// optionally fill-in the test value with lots of data
for ($i = 0; $i < 100000; $i++) {
    $context['test'][$i] = $i;
}
// you can also just create a big string
// $context = str_repeat(' ', 1000000);

// benchmark
$time = microtime(true);
for ($i = 0; $i < 100; $i++) {
    // the snippet of code to benchmark
    $tmp = isset($context['test']) ? $context['test'] : '';
}
printf("TIME: %0.2d\n", (microtime(true) - $time) * 1000);

Note that the absolute performance numbers are meaningless here. We just want to compare the speed between different snippets.

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.

When you write a statement like $tmp = $context['test'], very little happens: the $tmp variable just becomes a reference to the $context['test'] one; that's why it's really fast. But as soon you want to modify the variable, PHP needs to copy the original one:

$tmp = $context['test'];

// the copy happens now
$tmp[] = true;

// copy also happens if the original variable changes
// $context['test'][] = true;

To sum up, the speed of the ternary operator is directly related to the time it takes to copy the result of the statement, even if it is not strictly needed. And copying an array of 100000 elements takes time.

If you are using PHP 5.3, there is a simpler way to express our statement with the new ?: construct:

$tmp = $context['test'] ?: '';

Unfortunately, this new construct has the same drawbacks as the standard one as far as performance is concerned, even if PHP should probably be able to optimize the case where the variable exists.

Yes, there is negligible difference between the two.

However the difference is so small that it doesn't matter which one you use (I prefer if/else) because they help in readability which would save you a lot of time if someone is going through your code or maybe you yourself are maybe after say 3 months or so.

For those people who want to check the difference try this code:

// declarations  
var num1 = 10, num2, i = 0, startTime, endTime, x, y;

// start timer
startTime = Math.floor((new Date()).getTime());

for(; i < 1e8; i++) {
  // first part if /else
  if(x == 10)
    y = x;
  else
    y = 0;

  // second part ternary
  y = (x == 10) ? x : 0;
}

// end timer     
endTime = Math.floor((new Date()).getTime() - startTime);
document.write("Time taken " + endTime + " ms");  

Note: Comment one of the part and execute the code and run the loop for large number of iterations (above code millions of iterations).

Tip: Try running the loop multiple times to get average.

When performing comparisons and conditionals, the ternary operator is a conditional operator that reduces the length of code. This approach can be used instead of if-else or nested if-else statements. This operator is executed in the following order: left to right, left to right, left to right, left to right, left to right, left to right, It is, without a doubt, the best case for a time-saving solution.

With its conditionals, it also generates an e-notice when it encounters a void value. It's known as a ternary operator because it has three operands: a condition, a true result, and a false result.

The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.

When the condition evaluates to real, the ternary operator will use its left-hand operand. This may be a string, an integer, a Boolean, or something else entirely. For so-called "false values," the right-hand operand will be used.

An empty array or string, null, an unknown or unassigned variable, and, of course, false itself are examples. The ternary operator will use its right-hand operand for both of these values.

Syntax:

(Condition) ? (Statement1) : (Statement2);

Parameters:

The expression to be evaluated that returns a boolean value is called the condition.

Statement 1: This is the statement that will be executed if the condition is valid.

Statement 2: This is the statement that will be executed if the condition is false.

Code:

$age=19;

print ($age>=18) ? "eligible for vote" : "not eligible for vote";

?>

Explanation:

In the above code a ternary operator has been implemented on the line ($age>=18)? “eligible for vote”: ”not eligible for vote” consists of three parameters as discussed above in syntax condition 1, if $age>=18 is a conditional statement if it is true statement 1 eligible for vote will be printed if condition is not true not eligible for vote will be executed.

Output:

TernaryOperator_1 

What to Use the Ternary Operator

When we need to simplify if-else statements that simply allocate values to variables based on a condition, we use the ternary operator. The use of a ternary operator reduces the large if-else block to a single line, improving readability and simplifying the code. Quite useful for assigning variables after a form has been submitted.

Just imagine the following code written with simple if else statements as follows

Code:

$score=40;

if ($score>=50){

echo "The result is pass" . "\n";

echo "congratulations" . "\n";

}

else{

echo "The result is Fail". "\n";

echo "Better luck next time" . "\n";

}

?>

Explanation:

In the above example, just use the simple if else statement. If the score is greater than 50 it tends to print the result as pass and congratulations. If the condition is false, it will print the statement under else as the result is fail and better luck next time.

Output:

TernaryOperator_2.

Instead of this, just use a ternary operator to reduce the coding.

Alternative for Reducing the Code

Code:

$score=40;

print($score>=50) ? "The result is pass congratulations" : "The result is Fail Better luck next time "

?>

Output:

TernaryOperator_3.

Advantages of Ternary Operator

  • It will shorten the code.
  • It will improve the readability of the code.
  • The code becomes more straightforward.
  • Makes basic if/else logic easier to code.
  • Instead of breaking your output building for if/else statements,you can do your if/else logic in line with output.
  • Shortens the code
  • Makes it faster and easier to manage code.

Ternary Shorthand

For fast shorthand evaluation, short ternary operator syntax can be used by omitting the middle part of the ternary operator. Elvis operatory (? ) is another name for it.

Elvis operator can be used to reduce redundancy in your situations and shorten the time it takes you to complete your assignments. It's the ternary operator, but without the second operand. If the operand is valid, it returns the first operand; otherwise, it evaluates and returns the second operand.

Syntax:

Exp1 ?: Exp2

Exp1 refers to expression1

Exp2 refers to expression2

Code:

print $start = $start ?: 1;

?>

Output:

TernaryOperator_4.

Ifselseif Else or Ternary Operator to Compare Numbers PHP?

Both are the same but professionally it is better to choose a ternary operator.

For example we need to compare two values

$val1=10

$val2=20

Code:

$val1=10;

$val2=20;

$da1=55000;

$output=$val1 ? $val2 : $val2 ? : $da1;

echo "The value is=",$output;

?>

Output:

TernaryOperator_5 

Null Coalescing Operator

It replaces the ternary operator when used with the isset() function, which checks whether a variable is NULL or not and returns the first operand if the variable exists and is not NULL, otherwise the second operand is returned.The Null coalescing operator checks whether a variable is null and returns the non-null value from a pair of personalized values. The Null Coalescing operator is primarily used to prevent the object feature from returning a NULL value instead of a default optimized value. Since it does not emit E-Notice during execution, it is used to prevent exceptions and compiler errors.The execution order is from right to left. If the right side operand is not null, the return value is the right operand; if it is null, the left operand is the return value. It makes the source code easier to understand.

Syntax

(Condition) ? (Statement1) ? (Statement2);

Alternative Method:

if ( isset(Condition) ) {  

return Statement1;

} else {

return Statement2;

}

Code:

// Coalescing Operator

$num = 10;

// Use Null Coalescing Operator

print ($num) ?? "NULL";

?>

Output:

TernaryOperator_6. 

Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

Using if/else and switch/case statements to evaluate conditions is an essential part of programming. If/else statements are simple to code and can be used in any language. If/else sentences are useful, but they may become excessively long. Ternary operator logic is the method of shortening your if/else structures by using "(condition)? (true return value) : (false return value)" statements.

We hope you find the information provided to be helpful. Join Simplilearn's Post Graduate Program in Full Stack Web Development to learn more about PHP and accelerate your career. In just a few months of intensive training with Simplilearn, you will have mastered modern coding approaches at bootcamp speed, and you will become a full-stack programmer.

You can also learn a number of job-ready courses from the global experts via Skillup for free. Simplilearn's SkillUp is an online platform where users can take free online courses in various subjects. All these courses are absolutely free! Explore them here and get back to us in case of any queries.

Leave your questions in the comments section of this article, and one of our experts will respond as soon as possible!

Which is faster ternary or if

In terms of speed there should be no difference.

Is ternary operator faster than if statement?

Yes! The second is vastly more readable.

Which is better ternary operator or if

If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion).

Is ternary operator faster than if JS?

There is no difference in speed. Some prefer the if/else for readability. Personally, I use the ternary operator whenever the logic is trivial enough to understand on one line.