It depends on what you’re doing, it’s not so simple to answer that, just looking at each case could make a decision, and everything after measuring, because it’s not always intuitive.
Contrary to what many people think, basic processing is cheap, access to memory is expensive, very expensive, it’s orders of magnitude. The more you avoid access to memory the faster your application becomes, so apply tricks that help the processor not access the main memory (I won’t even mention the mass memory because then the difference becomes brutal) and access the processor’s own memory (cache)or even that and get everything done in the register, the faster it gets.
But you have to be careful with this thing of creating variable to generate access to memory. This may not happen, in fact the variable may even disappear in the compilation if it is not necessary. And if you need something intermediate there will be a cost equal to what you had creating a variable even if your code has no variable at that point.
The programmer’s intuition does not always work, even when he has deep knowledge of the functioning of the computer, operating system, computation and other elements, imagine who does not have.
The most important thing is to test in that situation, because a change may already change everything. What’s more, this may not even be the reason to slow down or not. Who knows if you’re allocating string where you shouldn’t, or even if you need to, if there’s a copy... there’s so much that can affect more than that. Anyway, it’s not the variable in itself that will become the problem is the object.
Now, the question is a little strange when it comes to creating variables within a struct
because it’s the only thing you can create in her.
Creating a separate function or not is another matter. In general I say you should do what is most readable and then think about performance. But if you’re doing things in main()
should be something very simple, probably not a real concern to have.
If you can put as much as possible into stack, this is what seems to matter most to the case. Or inline if it makes sense (case of a struct
), but it doesn’t always fit.
Beware of the premature optimizations!
– Lacobus