This seems like a simple question to ask but, is it generally a good idea to re-use variables in any scripting language?
I'm particularly interested in the reasons why it is/isn't good practice as I'm besides my self if I should or shouldn't be doing it.
For example, $i
is one of the most common variables used in a loop to iterate through things.
E.g (in php):
//This script will iterate each entry in $array
//and output it with a comma if it isn't the last item.
$i=0; //Recycling $i
foreach ($array as $v) {
$i++;
if ($i<count($array))
{
echo $v.', ';
}
else {
echo $v;
}
}
Say I had several loops in my script, would it be better to re-use $i
or to just use another variable such as $a
and for any other loops go from $b
to $z
.
Obviously to re-use $i
, I'd have to set $i=0;
or null
before the loop, or else it would give some very weird behaviour later on in the script. Which makes me wonder if reusing it is worth the hassle..
Would the following take up more space than just using another variable?
$i=0; //Recycling $i
Of course this is the most simple example of use and I would like to know about if the script were terribly more complicated, would it cause more trouble than it's worth?
I know that re-using a variable could save a minuscule amount of memory but when those variables stack up, it gets important, doesn't it?
Thank you for any straight answers in advance and if this question is too vague, I apologize and would like to know that too- so that I know I should ask questions such as these elsewhere.
Resetting your variable ($i=0) is not going to take more space.
When you declare a variable (say of type integer), a predefined amount of memory is allocated for that integer regardless of what its value is. By changing it back to zero, you only modify the value.
If you declare a new variable, memory will have to be allocated for it and typically it will also be initialized to zero, so resetting your existing variable probably isn't taking any extra CPU time either.
Reusing an index variable for mutually exclusive loops is a good idea; it makes your code easier to understand. If you're declaring a lot of extra variables, other people reading your code may wonder if "i" is still being used for something even after your loop has completed.
Reuse it! :)