Hello, this is my first time here. I just discovered this place and think it's very great. I have a few questions to ask but I will start with this one.
I wonder which method below is more efficient.
First method
if($somesting){
......
......
}
Second method
if($somestring!=''){
......
......
}
The first method will need a type conversion while the second method need a comparation. Which one will use less cpu clock cycles?
Thanks
Type conversion and efficiency
Moderator: General Moderators
- CoderGoblin
- DevNet Resident
- Posts: 1425
- Joined: Tue Mar 16, 2004 10:03 am
- Location: Aachen, Germany
The best way of checking is to use empty($var)
You may also want to look up isset which is another useful function but not applicable to your question.
You may also want to look up isset which is another useful function but not applicable to your question.
Be careful!
I'd use whatever is more readable, and only worry for efficiency if it is inside a three-layered loop or something.
Code: Select all
$a = Array();
if ($a != '') echo 1; else echo 2;
if (!empty($a)) echo 1; else echo 2;
if ($a) echo 1; else echo 2;I prefer to be as explicit as possible.
If I'm checking for something that is not a particular value, I specify that exact value for comparison.
I rarely use something like:
Why? well, for a start - if $var is undefined, I will receive a notice error. Next, it's an ambigous challenge. If the value of $var is an empty array, (int) 0, (string) '' or (bool) false it will not execute the DoSomething(); function.
Thus, with an explicit comparison I can choose exactly which of the above I want:
In the above, I do an isset() first to avoid receiving a notice error.
If I'm checking for something that is not a particular value, I specify that exact value for comparison.
I rarely use something like:
Code: Select all
if ($var) DoSomething();Thus, with an explicit comparison I can choose exactly which of the above I want:
Code: Select all
if (isset($var) && $var === '') DoSomething();