Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Efficiency and indicating argument types

I have three related questions about specifying types of function arguments and outputs. I'm defining a function f that I expect to call many times, so I'm looking to improve efficiency everywhere I can. My function definition looks something like this:

function f(x, y)
    ...
    return z
end

I know that x will be an Array{Float64,1}, y will be an Array{Float64,2}, and z will be a Float64.

My questions are:

  1. Is there an efficiency benefit to specifying the types of the inputs in the function definition, i.e. function f(x::Array{Float64}, y::Array{Float64})?
  2. Is there any additional benefit to making the types more specific by specifying that x is 1-dimensional and y is 2-dimensional, i.e. function f(x::Array{Float64,1}, y::Array{Float64,2})?
  3. Is there any efficiency benefit to specifying the type of z, i.e. function f(x::Array{Float64,1}, y::Array{Float64,2})::Float64?

Thanks so much! And apologies if these questions have been addressed previously.

like image 541
A. Harris Avatar asked Dec 18 '22 11:12

A. Harris


1 Answers

In general, no (to all questions). The beauty of Julia is that its compiler is excellent at figuring these things out for you on the fly. The performance tips is the best place to look for how to write efficient code, like making sure your function is type-stable.

like image 147
Benoit Pasquier Avatar answered Dec 20 '22 00:12

Benoit Pasquier