Containers of abstract types are not performant,
This is documented in the performance notes section of the manual.

However containers of concrete types are not generic.
For example, I am currently redoing a large section of code from using 
Float64s to using Numbers, so that I can use DualNumbers to check 
derivatives.

The reason Number (and other abstract types) are slow, is because are full 
of pointers.
Since each element of a Matix{Number} could potentially be of a different 
type, eg some could be Int8s and some could be Float64s.
But in practice the varse majority of the time, every element is of the 
same type.

The 3 signitures:

Matix{Number}
Matrix{Union(Number, Float64, Float32, Float16, Int...) }
Matrix{T<:Number}


All can contain the same information, as they will all contain a 
Matrix{Number}, and none of them will contain a Matrix{NotNumber},
 (Though to fit a concrete typed matrix into a matrix of abstract type you 
need to run a convert),

But they have very different performance.
As I can show with the following Notebook:
http://nbviewer.ipython.org/gist/oxinabox/a00d3b1eb5584467e6b7
Which also compares with Any just for the sake of seeing if contrete types 
help (they don't)

What can be seen t Matrix{Union(Number, Float64) }, Matrix{T<:Number} and 
Any perform about the same
and that Matrix{Number} is 3 orders of magnitude slower (not unexpected).

Ergo, because the former can contain anything that can be contained in the 
Matrix{Number}, there is AFAICT, no reason not to use them.
Worse case senario, the contents really is a Matrix of mixed numeric types 
and the performance falls back to the Matrix{Number} case.

Syntactically perhaps it is less nice.
I have a type alias for Matrix{Union(Number, Float64,...)} which solves 
that, to an extent.
Argument could be made that Matrix{T<:Number} is even better, but it is 
annoying to refactor code to use that as it is not a simple find and 
replace as a type parameter needs to be added to all functions.


----

Thoughts, comments, 
Reasons why Matrix{Number} might be users over either of the other cases?


Reply via email to