1. Do not copy variables randomly
Sometimes in order to make the PHP code more neat, some novice PHP (including me) will copy the predefined variables into a shorter name of the variable, in fact, the result is an increase in memory consumption, will only make the program more slowly. Imagine, in the following example, if the user maliciously inserted 512KB bytes of text into the text input box, which will result in 1MB of memory consumption!
Bad:
$description = $_post[' description ');
Echo $description;
Good:
echo $_post[' description '];
2. Use single quotation marks for strings
The PHP engine allows the use of single and double quotes to encapsulate string variables, but this is a big difference! A string using double quotes tells the PHP engine to first read the string contents, look for the variable in it, and change the value to the variable. Generally speaking, strings are not variable, so using double quotes can cause poor performance. It is best to use a string connection instead of a double-quoted string.
Bad:
$output = "This is a plain string";
Good:
$output = ' This is a plain string ';
Bad:
$type = "mixed";
$output = "This is a $type string";
Good:
$type = ' mixed ';
$output = ' This is a '. $type. ' String ';
3. Use the Echo function to output a string
Using the Echo () function to print out the results is easier to read, and in the next example you can see better performance.
Bad:
Print ($myVariable);
Good:
Echo $myVariable;
4. Do not use connectors in Echo
Many PHP programmers (including me) do not know when to use the stench to output multiple variables, you can actually use commas to separate, instead of using strings to first connect them, as in the first example below, because the use of connectors will have a performance problem, because this will require the PHP engine first put all the The foot bath powder variable is connected and then in the output, and in the second example, the PHP engine will output them sequentially.
Bad:
Echo ' Hello, my name is '. $firstName. $lastName. ' and I live in '. $city;
Good:
Echo ' Hello, my name is ', $firstName, $lastName, ' and I live in ', $city;
5. Use Switch/case instead of If/else
For a single variable, using the Switch/case statement instead of the If/else statement will have better performance and the code is easier to read and maintain.
Bad:
if ($_post[' action '] = = ' Add ') {
AddUser ();
} elseif ($_post[' action '] = = ' Delete ') {
DeleteUser ();
} elseif ($_post[' action '] = = ' edit ') {
Edituser ();
} else {
DefaultAction ();
}
Good:
Switch ($_post[' action ']) {
Case ' Add ':
AddUser ();
Break
Case ' Delete ':
DeleteUser ();
Break
Case ' edit ':
Edituser ();
Break
Default
DefaultAction ();
Break
}
Five tips for optimizing PHP performance