I have a PHP file ajax.php
where i always send my ajax to. There are about 50 else if statements in the code. I always pass a POST Parameter cmd
to my ajax.php
file and check if the variable is set and execute different code depending on the variable content.
I was wondering if i should rather split my ajax.php
to multiple files to reduce the amount of else if
statements and increase performance. But how many else if
are we recommended to use and does it have a big impact on performance if we use eg 10000?
I don't think performance would be a problem with 50 or 100 different commands. But what i would suggest is to use switch case and functions, like this
$cmd = $_POST['cmd'];
switch ($cmd){
case "command1":
fnCommand1();
break;
case "command2":
fnCommand2();
break;
}
function fnCommand1(){
//do command 1
}
function fnCommand2(){
//do command 2
}
It would be easier to read and more manageable in case you decide to split it into files,
You can use key value pattern in php. Make a array with your post paramaters as key and other as s values. Whenever the paramater will come to ajax.php
check for the key using array_key_exist() Array key value and Array
i think that is barely insane to write 10k elseif by yourself, i would prefer to crack my head and find a valid algorithm, or use a switch
statement instead.
Btw, try always to avoid this kind of situation, doesn't really matter if is a single file or 1000 files, the processing time will always be the same
Separating file can not benefit performance but human readable and maintainable.
If your code is something like:
if($_POST["cmd"]=="a"){
//case a
}else if($_POST["cmd"]=="a"){
//case b
For performance, you can change it to switch case. But if statement optimization always not performance-critical.
PHP doesnt have performance issues with some many lines but people do. Maybe you can read the code because you remember it now. But if your somebody joins your team he will be lost and probably wont join because of that. Or if you came back to this script after a year would you be able to read it, add or delete something?
Every script or class schould do one thing or work with one entity. There are many approaches how to write better code.
single responsibilty principle
and many more
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.