I have a question efficient script structures. Lets say I have variables $a, $b and $c. I don't know if it matters what they contain, but just in case, lets say that these are set with the following functions:
Code:
$a = // something that requires a query to the database
$b = time();
$c = $_SERVER['REMOTE_ADDR'];
Now in my script, I have various if/else statements. These three variables will be used in some of the conditionals, but not all of them. So what I am wondering is which of the two following structures would be better.
A) declare the variables at the top, use them in the applicable places:
Code:
$a = $a stuff;
$b = $b stuff;
$c = $c stuff;
if(something)
{
do something with $a $b and $c
}
else
{
do something else
}
if(another thing)
{
do something
}
else
{
do something with $a $b and $c
}
if(one last thing)
{
do something with $a $b and $c
}
else
{
do something else
}
B) Declare the variables in the places they are to be used, then use them
Code:
if(something)
{
$a = $a stuff;
$b = $b stuff;
$c = $c stuff;
do something with $a $b and $c
}
else
{
do something else
}
if(another thing)
{
do something
}
else
{
$a = $a stuff;
$b = $b stuff;
$c = $c stuff;
do something with $a $b and $c
}
if(one last thing)
{
$a = $a stuff;
$b = $b stuff;
$c = $c stuff;
do something with $a $b and $c
}
else
{
do something else
}
Option A uses less code, as the variables are declared only once. However, they are declared whether or not they are necessary.
Option B uses more code, but the variables are only declared in the event that they are needed.
So which one of these do you think (or know) is more efficient, and why?
note: I'm kind of suspecting option B, as I think that servers can probably process more code in a script faster than they can process unnecessary queries to the database.