Is there some type that I can pass into functions that would indicate that I don’t care about the result?
The background is that I always try to write in place functions. When I have a, b, c = f(x, y, z)
I always implement it in terms of f!(a, b, c, x, y, z)
. Note that all variables are arrays. Currently, if I don’t need b
and c
, I still have to allocate memory for them and the function has to fill them.
Is there some type that I could pass to the function indicating that I don’t need the variables? Something like f!(a, nothing, nothing, x, y, z)
. The compiler could then produce a function that does not even do the computation for b
and c
, with code reduction and speedup as a result.
You can check for nothing
and not compute the output for those arguments, e.g.
function f!(a, b, c, x, y, z)
if a !== nothing
# fill a
end
if b !== nothing
# fill b
end
if c !== nothing
# fill c
end
end
Indeed, but the compiler could easily do it for me. My question was more about whether it is possible in Julia.
You could try to create a DevNullArray
and see what kind of codegen you get. This is untested, but something like
struct DevNullArray{T,N,Ax<:NTuple{N,<:AbstractUnitRange{Int}}}
axes::Ax
end
Base.setindex!(A::DevNullArray, v, I) = nothing
You’d need a few more methods, see https://docs.julialang.org/en/latest/manual/interfaces/#man-interface-array-1.
If you try this and really like it, consider contributing it to JuliaArrays.
4 Likes
Was just about to post essentially the same thing. Seems like it would be slightly better to define setindex!
like so
Base.setindex!(A::DevNullArray, v, I...) = v
3 Likes
Thank you for pointing me in the right direction! Perhaps IgnoreArray
would be a better name?
1 Like
Personally, I love DevNullArray
.
I would intepret IgnoreArray
as an indication that one should ignore the array, which isn’t accurate.
1 Like
Note that this will cause code that reads from this array to break completely. Is probably obvious, but worth stating that you should only do this if you know how the function works.
Another option is WriteOnlyArray
. If reading is an error, well, then of course you can ignore the writes.
1 Like
While this is fun to brainstorm about, I believe that it will be very unlikely that everything folds down into nothing when using such an array in more complicated contexts. So just accepting a Union{AbstractArray, Nothing}
and branching is most likely the way to go in practice.
6 Likes