Skip to content

global variables are unpredictably slow (codegen inference issue) #42559

@bvdmitri

Description

@bvdmitri

Consider two functions:

function foo(::Type{T}) where T
    return (v) -> T(v)
end

function bar(::Type{T}) where T
    R = T
    return (v) -> R(v)
end

while these functions semantically should do the same, their performance is drastically different:

julia> f = foo(Int)
#9 (generic function with 1 method)

julia> b = bar(Int)
#11 (generic function with 1 method)
julia> @btime f(1)
  13.685 ns (0 allocations: 0 bytes)
1

julia> @btime b(1)
  98.902 ns (0 allocations: 0 bytes)
1

This happens because Julia cannot infer correctly the type in the second case, which results in bad performance overall.

julia> dump(f)
#9 (function of type var"#9#10"{Int64})

julia> dump(b)
#11 (function of type var"#11#12"{DataType})
  R: Int64 <: Signed

Provided MWE seems to be very simple, but we hit this performance issue in a very complex code involving a lot of lambda functions. @cscherrer faced similar issue in his MeasureBase.jl package.

julia> versioninfo()
Julia Version 1.6.3
Commit ae8452a9e0 (2021-09-23 17:34 UTC)
Platform Info:
  OS: macOS (x86_64-apple-darwin19.5.0)
  CPU: Intel(R) Core(TM) i7-7660U CPU @ 2.50GHz
  WORD_SIZE: 64
  LIBM: libopenlibm
  LLVM: libLLVM-11.0.1 (ORCJIT, skylake)

Reproducible on master 146de38 as well (same hardware).

Metadata

Metadata

Assignees

No one assigned

    Labels

    performanceMust go fasterregressionRegression in behavior compared to a previous versionregression 1.12Regression in the 1.12 release

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions