-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Unexpected allocation on ternary operation #56893
Comments
Given you description it makes sense that it allocates the storage for the output? |
Right but the type instability is still handled without allocations if e.g. struct B
val::Bool
unrelated::Int
end
b = B(true, 2)
@btime f($b);
# 2.691 ns (0 allocations: 0 bytes)
@btime g($b);
# 2.065 ns (0 allocations: 0 bytes) It is confusing to not know what will allocate or not |
Hm, I see, that's indeed confusing, just to add to the collection: julia> mutable struct C
val::Bool
unrelated::Int
end
julia> c = C(true, 2)
C(true, 2)
julia> @btime f($c)
1.666 ns (0 allocations: 0 bytes)
C(true, 2)
julia> @btime g($c)
1.666 ns (0 allocations: 0 bytes)
C(true, 2)
julia> mutable struct D
val::Bool
unrelated::Base.RefValue{Nothing}
end
julia> d = D(true, Ref(nothing))
D(true, Base.RefValue{Nothing}(nothing))
julia> @btime f($d)
1.666 ns (0 allocations: 0 bytes)
D(true, Base.RefValue{Nothing}(nothing))
julia> @btime g($d)
1.666 ns (0 allocations: 0 bytes)
D(true, Base.RefValue{Nothing}(nothing)) Interestingly enough making the struct mutable also eliminates the intermediate allocation. |
Julia structs aren't |
I was surprised to see that the ternary operation creates an allocation in this example. Should this be considered a bug?
The behaviour has at least these three requirements:
A
contains a non-isbitstype member typef
has unstable output typef
has one branch returning anA
instanceIf any of them is not satisfied, no allocation happens.
The text was updated successfully, but these errors were encountered: