From Performance Tips:
When working with parameterized types, including arrays, it is best to avoid parameterizing with abstract types where possible.
Suppose you're writing a function that requires a Vector, and with each use of the function, the Vector can contain different types.
function selection_sort!(unsorted_vect::AbstractVector)
# Code to sort.
end
names = String["Sarah","Kathy","Amber"]
unsorted_fibonacci = Int32[8, 1, 34, 21, 3, 5, 0, 13, 2, 1]
selection_sort!(names)
selection_sort!(unsorted_fibonacci)
When using selection_sort!() the first time, the Vector contains String, the second time Int32.
The function knows it's getting an AbstractVector, but it doesn't know the type of elements.
- Will performance be inefficient? Would it be the same as writing
selection_sort!(unsorted_vect::AbstractVector{Real})?
The same section also says:
If you cannot avoid containers with abstract value types, it is sometimes better to parametrize with Any to avoid runtime type checking. E.g. IdDict{Any, Any} performs better than IdDict{Type, Vector}
- Would it be better to write the function this way?
function selection_sort!(unsorted_vect::AbstractVector{Any})
If so, why do the sorting algorithms just use AbstractVector?
function sort!(v::AbstractVector, # left out other parameters)