Page 1 of 1
Type conversion and efficiency
Posted: Mon Sep 04, 2006 3:44 am
by Muyong
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
Posted: Mon Sep 04, 2006 4:00 am
by CoderGoblin
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.
Posted: Mon Sep 04, 2006 5:58 am
by Mordred
Be careful!
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'd use whatever is more readable, and only worry for efficiency if it is inside a three-layered loop or something.
Posted: Mon Sep 04, 2006 6:48 am
by Jenk
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:
Code: Select all
if (isset($var) && $var === '') DoSomething();
In the above, I do an isset() first to avoid receiving a notice error.
Posted: Tue Sep 05, 2006 12:50 am
by Muyong
I'd use whatever is more readable, and only worry for efficiency if it is inside a three-layered loop or something.
Yes, I agree with you. Thanks for all comments.