Global Type-Locking

https://github.com/JuliaLang/julia/issues/8870

I just ran (forgetfully) into the global performance issue. after it has bitten me often enough, I will probably remember it.

I cannot use a const, because I need to change the value. But I do not need to change the type. If I could just tell julia constT that the type is constant, I am guessing that the compiler could generate better code, and my code would be less buggy, too.

Is there a plan to create a mechanism that allows fixed typing of a global?

This can already be done by using a const binding to mutable (but well-typed) state:

julia> const MY_CONST = Ref{Int}()
Base.RefValue{Int64}(4545197904)

julia> MY_CONST[] = 1
1

julia> MY_CONST[]
1

julia> MY_CONST[] = 2
2

julia> MY_CONST[]
2

This should be as performant as any built-in implementation could possibly be, AFAIU.

4 Likes

in this case, could one define a constT that makes this all transparent to users of julia, and add it into the language?

The plan here is to allow var::T in global scope to constrain the type of var to being T much like you can created typed locals with the same syntax in local scopes. The implementation will likely be that var is stored in a const typed Ref since that behaves in the right way already and just has less convenient syntax.

2 Likes

with less conveint syntax

julia> mutable struct Global{T}
           value::Ref{T}

           function Global(x::T) where {T}
               return new{T}(x)
           end
       end

julia> Base.getproperty(x::Global{T}, sym::Symbol) where T = getfield(x,sym)[]

julia> Base.show(io::IO, x::Global{T}) where {T} = show(io, x.value)

julia> globalint = Global(5)
5

julia> globalint
5

julia> globalint.value = 6
6

julia> globalint
6

What’s the goal of this implementation?

FWIW, globalint.value is longer than globalint[]

Also, Ref isn’t a concrete type. Global doesn’t need to be mutable, and the field type doesn’t need to be Ref anyway…

no goal – just wondered how far current syntax would go.
It also does not allow use like b = a + globalint

fantastic. planned for 1.5? 2.0?

It’s a non-breaking change so it would be in some 1.x release.

1 Like