I have a program that runs fine. I want it to run faster. So I redefined some of its top-level variables to be const, like this
const myvar = 1
Now when I run the program I get the following message:
WARNING: redefinition of constant myvar. This may fail, cause incorrect answers, or produce other errors.
Before changing some variables to be const my if I just redefined the values of some variables, selected the whole code in the editor, and hit Ctrl_Enter, the program would run fine and yield me the correct values. I could do this many times, and did not have to start a new session.
Should I be worried that the program will not always run correctly just because some variables have been defined as const?
Both declaring a constant and performing type annotation help the compiler optimize by conveying the following information: the global variable/constant will not change its type at runtime.
So, for all intents and purposes I think is safe to assume the two approaches will have equal performance. Also, you can benchmark to ensure that happens for your use case.
This answers my question. However, oddly, I created a new version of my program with all the consts removed, but leaving the type declarations. This version runs about 5% faster (!) than the original version with consts and type declarations. I tried several times and this happened consistently.
Possible explanations:
Increased compilation time due to the consts.
At run time having to check if there were changes. (Although I think this would be the same in both cases)