Reuse of variables

Asked

Viewed 346 times

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:

  1. All languages (or most languages) allow this variable reuse?
  2. This is good practice?
  3. 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?
  • 4

    Strongly typed languages, such as java, with no chance of this occurring, further reusing different types.

  • @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 meant with the examples cited in the question. No chance of a variable String turn Boolean so out of the blue in java.

  • 4
    1. No; 2. It lacks the definition of good practice; 3. In general there is no and, even if there is, it is not worth losing readability for a possibly tiny gain.
  • @LINQ Obg! Clarifies the question. Thanks!

    1. Not all, because strongly typed ones only allow the variable to store values of one type or subclasses of the same class. 2) No, this eliminates the clarity of the code. 3) No, most of the time the benefit is negligible, only if.
  • @RHERWOLF cool! Obg for explanations.

  • 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.

Show 3 more comments

2 answers

14

I assume that the more the code is dried, the faster the algorithm will be compiled and executed

This is not an absolute truth, the way most people who code in Javascript tend to slow the code down precisely because it is dry. It also occurs in other languages, but in JS it is usually worse.

From the point of view of readability should not reuse variables to do more than one thing, there is no benefit of performance if done well. But in the example it makes little difference because the name is already bad (I know it’s just example, but the question speaks in good practice and coding style, so the example is not good).

The first example is terrible for readability, any future maintenance tends to create some problem if it ends up needing the variable somewhere else and the programmer does not realize that it is reused.

All languages (or most languages) allow this variable reuse?

If the value is of the same type all allow, has no way the language understand its intention, there is no way the compiler know that it is a reuse. If it’s any other kind, just the language of dynamic typing allow.

This is good practice?

Many already know what I think about the subject and I have even lecture devoted criticizing good practices. But in general it should not do this, it is very difficult to justify the reuse of the variable, and I doubt that someone produces more than lame excuses or arguments without foundation to indicate the use. Of course, in a specific technology there may be something I don’t know beforehand that can justify.

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?

The gain, when there is, will be derisory. In language of script the gain will be greater, however, is what I always say, who chose a language of this type does not want to save resources, otherwise made a wrong option and then everything will be gambiarra, already in language more systems or Nterprise They will have minimal or non-existent earnings, especially if the person knows what they are doing. The economy depends on the adopted technology and even on its version or some configuration.

In languages with scope correctly implemented the second example does not work either because the variable created within the if there is only there.

  • Yeah, the scope thing I got. In case I used let I would have to declare the variable outside the if. But it was just any example. : )... But good explanations, I am absorbing the information. Obg!

  • Don’t take this the wrong way, but I think you have gone beyond the question, as in the last paragraph. rs.. I gave just one example, as I pointed out, "hypothetical". Among other statements I do not agree, but I will not get into controversy. I absorbed what is absorbable.

  • 5

    @Sam’s question is about coding style, and about good practice, you can’t talk about it properly with hypothetical artificial examples properly. If I just ignore these problems in the code, including the others I said, whoever reads this will think that the example is good and will start doing so. One of the reasons people program so badly is because they always see poorly crafted hypothetical examples. They cannot discern what is artificial and what is real. The biggest reason why almost no one knows OOP (almost all examples are artificial)

  • As I said, I won’t get into controversy. Abs!

  • 2

    @Sam not to get into polemics you should not say anything, when you speak already entered. Enter or is not your decision, just be consistent. And I think it’s a shame I don’t agree with other things because all I’ve said are facts or things consecrated by all the best programmers (other than the fact of not following good practices, but that when one sees my talk always agrees, it is just not consecrated because it is not something universally spoken). As he did not specify I do not know if he disagrees with the facts or the consecrated ones. But again each programmer writes his codes as he wants.

  • Maniero, give a read on my last comment. I wish you the best day you can have in life. Abs!

  • 4

    @Sam I read and I answered just about that, I think you didn’t read mine to repeat what you said. You’ve been lecturing that you’ve learned a lot, but that doesn’t seem to be the case. If you’re going to write that you disagree with something and you’re not going to say what’s just dirty about your image, something that you have a lot to worry about, so either you don’t say anything, or you don’t say anything at all, otherwise the only purpose of having written it is cause for controversy, Just for the sake of argument, it’s not even to discuss a technical matter. Next time, it’s too late.

  • 4

    My complaint is just the inconsistency of saying that you don’t want to get into controversy and be the only thing you did writing this. Not accepting the answer is your right, I don’t care about that, people will read and know the content, that’s important. The reason for not accepting is another inconsistency, but it is your right.

Show 3 more comments

3


I assume that the more the code is dried, the faster the algorithm will be compiled and executed.

It already left of a wrong principle. There are several complicated algorithms that run fast precisely because they are sophisticated (e.g.: a sort algorithm that adapts to small, medium or large lists). And there are many lean but dumb algorithms that are slow to be simple (e.g.: a Bubble Sort, or a 1-line Fibonacci that uses two recursions and redoes an immense amount of calculations already made).

  1. All languages (or most languages) allow this variable reuse?

Not. Languages with static types will not allow the variable to change type. Functional languages with a focus on immutability will require you to create a new variable instead of the old one. In Erlang, for example, you will need to choose another name or use recursion. In F# you can do two or more Let x = ..., but they will be conceptually different variables (the last one hides the previous one).

  1. This is good practice?

Not, not at all. If you have another concept, better use another name (therefore another variable). Perhaps it would be good practice on 8 or 16 bit processors. Today, no more. It would only be justifiable to do this if it were tested and proven that in such a program, in such a language reuse saves crucial bytes for performance.

  1. 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?

Not also. Each variable can occupy a different amount of resources. It’s not going to be by saving variables that you will be able to improve performance, be it compilation, or execution.

Also, if you create small functions, you don’t have to worry about reusing variables, because anything you don’t return will cease to exist at the end of the function (or soon after, once the Garbage Collector runs)!

Remember that a byte does not occupy the same as an Object, which does not occupy the same as a Memorymappedfile or Socket, so the number of variables is the least important. In the case of files or sockets, what would save resources would be to close them (with .close() or something equivalent) as soon as they are no longer used. Reusing the variable would have a negligible effect, because what really consumes/releases resources are the procedures of opening/closing the files or connections.

Another example that explains why not reuse variables are the JITs: if the JIT compiler observes that you have only declared Function f() {...}, it can efficiently call the function with a few additional checks. However, if in the same code you do f = 1.0; or delete f; the code will need to be disoriented to first check the type of f, call it if it is a function or generate "f is not a Function" or "f is not defined" otherwise. This is one of the reasons why Javascript’s "use Strict" prohibits the programmer from redefining essential language elements (such as eval or arguments) and call delete in some situations. Very dynamic situations are a hindrance for optimizers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.