Page 1 of 1

Optimising a 1 line piece of code

Posted: Thu Jun 19, 2008 2:41 am
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).

Re: Optimising a 1 line piece of code

Posted: Thu Jun 19, 2008 2:44 am
by Kieran Huggins
we'll need to see the larger picture. Example?

Re: Optimising a 1 line piece of code

Posted: Thu Jun 19, 2008 3:15 am
by onion2k
Optimising means making the code run more efficiently, it's got nothing to do with writing less code.

Re: Optimising a 1 line piece of code

Posted: Thu Jun 19, 2008 5:55 am
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.

Re: Optimising a 1 line piece of code

Posted: Mon Jun 23, 2008 6:44 am
by Walid
Thanks for your responses.

(p.s. Sorry not to have come back to you earlier because I never received any notification emails.)

Re: Optimising a 1 line piece of code

Posted: Mon Jun 23, 2008 7:36 am
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.

Re: Optimising a 1 line piece of code

Posted: Mon Jun 23, 2008 9:53 am
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.