Performance of abstract argument in methods

It occurs to me, maybe mistakenly, that there is a tendency to believe that being precise with your type arguments in functions also gives you performant code. Performance Tips doesn’t explicitly mention something like that. I myself also cannot find reasons to agree with such a statement.

In my view having abstract arguments (or even ::Any) will just oblige Julia to compile at run-time a more precise implementation of the function (aka method). So it doesn’t really make a difference, since even if I define a more precise method it will not be compiled until I call it (without considering precompilation tactics). And as long as the compilation is done, run-time execution will be the same for both cases. right?

So I would even dare to say that for readability reasons, it would be good to try to have as much abstract arguments as possible, as long as all the operations in the function body are being supported from all the type subset.

I hope posting a question here will yield a final answer and remove any doubts.

Correct - type declarations in arguments are (almost all of the time) only used for informing dispatch. The only exception I know of is when julia avoids specialization on purpose, all other cases are always specialized depending on the runtime type (if statically inferred, ahead of time, otherwise dynamically at runtime).

To be clear here - annotating types in arguments does (almost) never improve performance (and probably never in the cases you’re thinking of). In the vast majority of cases it will only limit the types of objects allowed to be put in (which may be a smaller set than what could actually be put in based on the functions that operate on any given argument).

6 Likes

This is discussed in more detail by the Julia 1.7 manual: https://github.com/JuliaLang/julia/blob/master/doc/src/manual/functions.md#argument-type-declarations

3 Likes