On Wednesday, April 13, 2016 at 1:14:42 PM UTC-4, James Fairbanks wrote: > > What is the best way to express this in types? Does > Union{Associative{Int,T}, AbstractArray{T}} express this with no > performance penalty? Is there any reason to avoid Union types? >
Unions have no better or worse performance than any other abstract type. Whether there is any performance impact at all depends on the context. 1) In a function argument, type declarations have zero effect on performance. It doesn't matter to the compiler whether you declare a function as f(a), f(a::Any), f(a::Vector{Float64}), or f{T}(a::Union{Associative{Int,T}, AbstractVector{T}}). The key thing to remember about Julia is that, each time you call a function f(a) with a different type of argument, Julia recompiles a new version of f specialized for that argument type, which is used for all subsequent calls for the same argument types. This specialized version is just as fast as if you had explicitly typed f(a::SomeType) in the first place. Argument-type declarations are not for performance in Julia, they are a filter: they say "use this method for these types". This is useful for multiple dispatch (if you have different methods depending on the argument types), for correctness (if your function will give unexpected/incorrect results for some types), and for clarity (to indicate clearly to the user what is expected to be passed to a function). (I feel like this should be added as an "anti-tip" to the performance tips in the manual: don't declare argument types for performance reasons). 2) When you define a data structure, any abstract type for a field (whether it is a Union type or another abstract type like Associative) will be significantly slower than a concrete type. See: http://docs.julialang.org/en/latest/manual/performance-tips/#avoid-fields-with-abstract-type