Type conversion and efficiency

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Muyong
Forum Newbie
Posts: 2
Joined: Mon Sep 04, 2006 3:25 am

Type conversion and efficiency

Post 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
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post 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.
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Post 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.
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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:

Code: Select all

if ($var) DoSomething();
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.
Muyong
Forum Newbie
Posts: 2
Joined: Mon Sep 04, 2006 3:25 am

Post 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.
Post Reply