Optimising a 1 line piece of code

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
Walid
Forum Commoner
Posts: 33
Joined: Mon Mar 17, 2008 8:43 am

Optimising a 1 line piece of code

Post by Walid »

Does anyone know, is there a way of optimising this:

if($b) $a = $b;

Thanks.

p.s. (In case you're wondering why I'd want to optimise that, $b can often be a member of a huge multidimensional array and I'm trying to avoid rewriting such a long string twice).
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Optimising a 1 line piece of code

Post by Kieran Huggins »

we'll need to see the larger picture. Example?
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Optimising a 1 line piece of code

Post by onion2k »

Optimising means making the code run more efficiently, it's got nothing to do with writing less code.
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: Optimising a 1 line piece of code

Post by Apollo »

If $a is not expensive to restore, you could do

Code: Select all

$c = $a;
if (!($a=$b)) $a = $c;
Although I'm not sure if the compiler doesn't evaluate the expression more than necessary, once to assign it to $a and then convert it to a boolean result.

If $b is only expensive to retrieve, but not something 'heavy' to store or reassign, you could ofcourse do

Code: Select all

$tmp = $b;
if ($tmp) $a = $tmp;
Although it's very unlikely that this would perform better than the code above.
Walid
Forum Commoner
Posts: 33
Joined: Mon Mar 17, 2008 8:43 am

Re: Optimising a 1 line piece of code

Post by Walid »

Thanks for your responses.

(p.s. Sorry not to have come back to you earlier because I never received any notification emails.)
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: Optimising a 1 line piece of code

Post by Kieran Huggins »

I should add the old axiom "beware of premature optimization".

Also, someone once said "clever code is bad code" in the context of code maintenance.

Personally, I tend to try and make things as clear and simple as possible. My first crack at refactoring is almost always in SQL queries, as this is where you'll typically see the most performance gain.

Just get it done first; worry about performance when you need to scale.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: Optimising a 1 line piece of code

Post by Ambush Commander »

There's no need to optimize the statement; PHP will do it for you. PHP will not allocate new memory and copy the value of $b until you try to edit it.
Post Reply