Any language: Recycling Variables

This seems like a simple question to ask, but is it usually a good idea to reuse variables in any scripting language?

I am particularly interested in the reasons why this is / is not good practice, since I am apart from myself if I should or should not do this.

For example, it $iis one of the most common variables used in a loop to iterate through things.

For example (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;
    }
}

Let's say I had several loops in my script, it would be better to reuse $ior just use another variable, such as $a, and for any other loops - from $bto $z.

, $i, $i=0; null , script. , .

, ?

$i=0;    //Recycling $i

, , , script , , ?

, , , , ?

, , , , , .

+3
5

($ = 0) .

(, integer), . , .

, , , , , .

- ; . , , , , "i" - .

!:)

+1

, "", "". ASCII Unicode, . - . , , .

, , , . , .

, . , , , , . , .

, , , ( ) reset , .

+2

$i 0, foreach, , . , .

, for. PHP foreach , 0 :

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

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

, :

, , , , ?

, . , . ( ) / , . .

+2

/ , , .Net, for - , .

, - ( , )

- excel, - , script. , .

, , , , . , .Net, , ...

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

MyString, .

, ( , .Net):

Dim SomeString = SomeVariable & " " & SomeOtherVariable

SomeVariable, SomeVariable + " ", SomeVariable + " " + SomeOtherVariable - SomeVariable 3 .

, , . - , - , / .

: -

+1

, .

When using PHP (and other scripting languages), unset () should be considered for variables such as arrays or long strings. You should not worry about reusing or discarding small variables (integer / boolean / etc). It just isn't worth using the (slow) scripting language.

If you are developing a performance-critical application in a language with a lower (lower) level, such as C, it is more important to reuse the variable.

+1
source

Source: https://habr.com/ru/post/1775008/


All Articles