Skip to content

Inference failure on mean with a subarray #160

Open
@pdeffebach

Description

@pdeffebach

I am working on a PR to Missings.jl where I construct a subarray manually. See the PR here

I've been trying to debug inference issues using the mean function. I thought that my implementation was wrong. But now I see that mean is actually type-unstable in this instance!

Is there anything that I should do to recover type stability? Is that I'm doing kosher at all?

julia> x = [1, 2, missing]
3-element Vector{Union{Missing, Int64}}:
 1
 2
  missing

julia> function nomissing_subarray(a::AbstractVector, nonmissinginds::AbstractVector)
           T = nonmissingtype(eltype(a)) # Element type
           N = 1 # Dimension of view
           P = typeof(a) # Type of parent array
           I = Tuple{typeof(nonmissinginds)} # Type of the non-missing indices
           L = Base.IndexStyle(a) === IndexLinear # If the type supports fast linear indexing
           SubArray{T, N, P, I, L}(a, (nonmissinginds,), 0, 1)
       end;

julia> t = nomissing_subarray(x, [1, 2])
2-element view(::Vector{Union{Missing, Int64}}, [1, 2]) with eltype Int64:
 1
 2

julia> using Statistics

julia> @code_warntype mean(t)
MethodInstance for Statistics.mean(::SubArray{Int64, 1, Vector{Union{Missing, Int64}}, Tuple{Vector{Int64}}, false})
  from mean(A::AbstractArray; dims) @ Statistics ~/.julia/juliaup/julia-1.9.0+0.x64.linux.gnu/share/julia/stdlib/v1.9/Statistics/src/Statistics.jl:164
Arguments
  #self#::Core.Const(Statistics.mean)
  A::SubArray{Int64, 1, Vector{Union{Missing, Int64}}, Tuple{Vector{Int64}}, false}
Body::Any
1 ─ %1 = Statistics.:(var"#mean#2")(Statistics.:(:), #self#, A)::Any
└──      return %1

julia> @which mean(t)
mean(A::AbstractArray; dims)
     @ Statistics ~/.julia/juliaup/julia-1.9.0+0.x64.linux.gnu/share/julia/stdlib/v1.9/Statistics/src/Statistics.jl:164

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions