PHP and Ternary Performance
The conditional statement is foundational in most programming languages. The ability to control the flow of a program makes decision-making in code a possibility. While there are a variety of conditionals across different programming languages, a few remain the same. The "if" statement is one of these statements, and often its shorthand version, the "ternary" operator, is as well. However, while the ternary gives programmers a simple way to express simple "if-else" statements, it does not always offer the same efficiency, as is evident in the PHP programming language.
-
PHP Conditionals
-
PHP conditionals help the programmer control the flow of a program during execution based on the state of certain variables. These conditional statements come in two basic forms: else-if conditions and loops. Important to this example is the else-if statement, which takes a conditional statement and evaluates a true or false value from it. Depending on that value, the statement will either perform a task, or perform another task. An else-if statement is like an "either-or" scenario. Either it performs a task or it does not.
PHP Ternary Operator
-
In order to make code more readable or easier to write, some conditionals have shorthand expressions. The shorthand for an "else-if" statement in PHP, and many other languages, is the "ternary" operator. The ternary operator in PHP uses a question mark and a colon as part of its syntax. The ternary operator evaluates a true or false term, and performs one of two operations based on that result. The following example illustrates a ternary expression: If statement 1 is true, then statement 2 executes. If not, then statement 3 executes:
(statement_1) ? statement_2 : statement_3;
-
Copy On Write
-
In most respects, the ternary operation is identical to a simple "else-if" statement. One particular difference is that ternary operators copy the return value of its statement evaluation each time it is read. The PHP language outside of this expression uses a technique known as "copy-on-write." This simply means that when assigning variables values, the PHP interpreter does not copy that value until the variable is modified. The variable just holds a reference to that value. The ternary operator, however, always copies the value.
Ternary Performance
-
Because PHP uses the copy-on-write technique, expressions such as an else-if statement do not repeatedly copy values when executed. A ternary operator, on the other hand, does. When performing a small number of operations, such as a single operation or a small loop, the performance difference between an else-if statement and a ternary statement is negligible. However, when operations continue to grow over large amounts of iterations, the ternary operator is shown to run much slower than a simple else-if statement.
-