Can @inline works when the inlined function is a field of a struct?

struct Cogg
    x::Function
end

fin(data::AbstractArray)=begin
    df=data .* 2
    @inline (i::Int)->begin
        #assume this body of function can not be inlined by julia automatically
        df[i]>0
    end
end

(cogg::Cogg)(n::Int)=begin
    x=rand(n)
    func=cogg.x
    for i=1:n
        func(i)
    end
end

cogg=Cogg(fin)
cogg(100)

Does the cogg.x is inlined in the loop body?

You would need to define

struct Cogg{F}
    x::F
end

so that the type of cogg.x is known at compile-time. This will lead to in-lining in some cases, for example:

julia> cogg = Cogg(x->2x)
Cogg{var"#1#2"}(var"#1#2"())

julia> f(c) = c.x(2)
f (generic function with 1 method)

julia> @code_llvm(f(cogg))
;  @ REPL[3]:1 within `f`
define i64 @julia_f_177() #0 {
top:
  ret i64 4
}
3 Likes

In julia v1.8, you can call @inline at the callsite as well

help?> @inline

  Give a hint to the compiler that calls within block are worth inlining.

  # The compiler will try to inline `f`
  @inline f(...)
  
  # The compiler will try to inline `f`, `g` and `+`
  @inline f(...) + g(...)

  │ Julia 1.8
  │
  │  The callsite annotation requires at least Julia 1.8.
3 Likes

Yes, after I append type parameters attached to Function field to each struct, the time has been speed up about 15%. Thanks

Yes, that is more intuitive, Thanks.