Does redefinition of const variables always create unpredictable behavior?

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?

Yes, if some constant value was folded on the compilation, your result may be wrong.

Just wrap all your code in a main function, or pass all data as parameters to your functions.

2 Likes

You can use typed globals if you want to get the performance improvement and not get into constant redefinition issues.

myvar::Int = 1
1 Like

That sounds like a perfect solution. Will one get the same performance enhancement from myvar::Int = 1 as one would get from const myvar::Int = 1?

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.

Yes.
The compiler can assume that something is a constant… for example…

type or paste code here

const SIZE = 3

function something(x)
     for i in 1:SIZE
           println(i)
     end
end

Could become


function something(x)
     println(1)
     println(2)
     println(3)
end

Now, this would work under the assumption that SIZE doesn’t change. When that assumption is violated… well… anything can happen.

1 Like

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:

  1. Increased compilation time due to the consts.
  2. At run time having to check if there were changes. (Although I think this would be the same in both cases)