4
I had a question about code optimization. I assume that the more the code is dried, the faster the algorithm will be compiled and executed.
Starting from this principle, I have the habit of reusing variables already declared. A simple example to illustrate, in Javascript would do the following:
var variavel = "Maria, João";
if(~variavel.indexOf("João")){
variavel = true;
}else{
variavel = false;
}
console.log(variavel);
whereas the initial value of variavel
will no longer be needed later in the code, I took it to reset true
or false
in another situation. Could have done so, declaring a new variable existe
and keeping the variable variavel
intact:
var variavel = "Maria, João";
if(~variavel.indexOf("Joao")){
var existe = true;
}else{
var existe = false;
}
console.log(existe);
This is just a hypothetical example, but consider an algorithm with hundreds of lines using this reuse of variables that structurally allow me to do this.
Without sticking to Javascript specifically, I would like to know about languages in general:
- All languages (or most languages) allow this variable reuse?
- This is good practice?
- There is considerable improvement in resource consumption (memory, compilation, execution), i.e., the fewer variables declared, the better the code in terms of resource consumption or performance?
Strongly typed languages, such as java, with no chance of this occurring, further reusing different types.
– user28595
@Articunol Python is strongly typed and allows this: https://answall.com/q/21508/101 If it is of the same type until Java allows.
– Maniero
@Maniero meant with the examples cited in the question. No chance of a variable String turn Boolean so out of the blue in java.
– user28595
– Jéf Bueno
@LINQ Obg! Clarifies the question. Thanks!
– Sam
– RHER WOLF
@RHERWOLF cool! Obg for explanations.
– Sam
In fact, languages such as C and C++, which allow to create scopes where you want and in them create local variables restricted to them offer a control of the time of life of variables, which allows a variable in a memory region to disappear and soon after that space can be occupied by another that goes through the same process, thus not needing to take the clarity of the code.
– RHER WOLF