In a scope that defines two variables a
and b
, the code firstly does things only on a
. Then a
is not used anymore. And it does things only on b
afterward.
A possible optimization is to deallocate a
before using b
, and allocate b
in the same memory location as a
(if they are allocated on the stack).
In C you could manually do this by grouping each of the two parts using braces. But are there languages or compilers that could automatically do this as an optimization? (I believed some compilers do, but found they don't.) I could accept constructors and destructors are not called in a reliable time sequence in such a language, or at least in the situations that support the optimization. But could it still be possible if there are pointers may or may not be pointing to the variable?
This was the code I was testing in gcc and g++:
#include<stdio.h>
int main(){
int a[2000000];
scanf("%d",&a[900000]);
printf("%d\n",a[900000]);
int b[2000000];
scanf("%d",&b[900000]);
printf("%d\n",b[900000]);
}
It segfaulted but would work with the b
part all removed. Adjust the numbers if your system had a different default stack size.
I did believe gcc has this optimization as the comments suggest, but it didn't pass the test, even with -O3
. Before knowing this, what I intended to ask was whether there are any advances (assuming it has existed in the first place) to this kind of optimization, with the new concepts such as ownership.
a
andb
. $\endgroup$a
handed to other (linked) code and so it obviously can't be reused. That isn't really an optimisation issue, it's just C semantics. I don't think this is necessarily a useful example for the rest of the question that is barely about that material element, but the emphasis could be shifted. $\endgroup$