开发者

Any language: recycling Variables

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.


I think you have "string" confused with "variable". A string is a collection of ASCII or Unicode characters, depending on the programming language. A variable is a named location in memory. So you are talking about recycling a variable, not a string.

Unfortunately, the way that variables are dealt with is highly language and compiler specific. You will get much better information if you give us more details.

Most languages have the concept of scope, with variable space being allocated at declaration and deallocated when the scope ends. If you keep a variable in its proper scope, you won't have to worry about wasting memory, as variables will be deallocated when no longer needed. Again, the specifics of scope are language dependent.

Generally, it is a bad idea to reuse variable names like that, as when (not if) you forget to reset the variable to some initial value within the same scope, your program will break at runtime.


You should be initializing $i to 0 before entering your foreach loop, regardless of whether you used it earlier in the function, and regardless of the language you're using. It's quite simply a language-neutral best practice.

Many languages help you enforce this by allowing you to bind the counting variable to the scope of the for loop. PHP's foreach provides a similar mechanism, provided your array is 0-based and contains only numeric keys:

foreach ($array as $i => $v) {
    echo $v;

    if ($i + 1 < count($array))
        echo ', ';
}

Also, in regards to your statement:

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?

No, it really doesn't. Variables will be garbage-collected when they fall out of scope. It's virtually impossible (without programatically generating code) to use so many counting/temporary variables through the course of a single function that the memory usage is at all significant. Reusing a variable instead of declaring a new variable will have no measurable impact on your programs performance, and virtually no impact on its memory footprint.


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! :)


Personally I donm't have any problem with reusing index/counter variables - although in some languages eg .Net, using a variable in a for loop specifically scopes the variable to that loop - so it's cleaned up afterwards no matter what.

You shouldn't ever re-use variables which contain any significant data (This shouldn't be an issue as all your variables should have descriptive names)

I once had to try to clean up some excel macro code written by a student - all the variable names were Greek gods and the usage swapped repeatedly throughout the script. In the end, I just re-wrote it.

You should also be aware that depending on the type of variable and the language you're using, re-allocating contents can be as expensive as creating a new variable. eg again in .Net, strings are immutable so this...

Dim MyString as String = "Something"
MyString = "SomethingElse"

Will actually allocate a new area of memory to store the 2nd usage and change the MyString pointer to point at the new location.

Incidentally, this is why the following is really inefficient (at least in .Net):

Dim SomeString = SomeVariable & " " & SomeOtherVariable

This allocates memory for SomeVariable then more memory for SomeVariable + " ", then yet again for SomeVariable + " " + SomeOtherVariable - meaning SomeVariable is actually written to memory 3 times.

In summary, very simple variables for loops I'd re-use. Anything else, I'd just assign a new variables - especially since memory allocation is usually only a tiny fraction of the time/processing of most applications.

Remember: Premature optimization is the root of all evil


This depends on the problem you are solving.

When using PHP (and other scripting languages) you should consider unset() on sizeable variables such as arrays or long strings. You shouldn't bother to re-use or unset small variables (integer/boolean/etc). It just isn't worth it when using a (slow) scripting language.

If you are developing a performance critical application in a low (lower) level language such as C then variable re-use is more important.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜