Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Annotating Types: Best practice for beginners

$
0
0

As a beginner I’m slightly unsure of when I should be annotating my code with types. I’ve read the section on types in the Julia manual and I’m happy with the basics (type hierarchy, parametric types, avoiding abstract types, and the importance of type stability) but I’m still slightly unsure how I should using type annotations in practice.

For instance, from the QuantEcon website:

You will notice that in the lecture notes we have never directly declared any types. This is intentional both for exposition and as a best practice for using packages (as opposed to writing new packages, where declaring these types is very important). It is also in contrast to some of the sample code you will see in other Julia sources, which you will need to be able to read. To give an example of the declaration of types, the following are equivalent. While declaring the types may be verbose, would it ever generate faster code? The answer is almost never.

function f(x, A)
    b = [5.0, 6.0]
    return A * x .+ b
end

val = f([0.1, 2.0], [1.0 2.0; 3.0 4.0])
function f2(x::Vector{Float64}, A::Matrix{Float64})::Vector{Float64}
    # argument and return types
    b::Vector{Float64} = [5.0, 6.0]
    return A * x .+ b
end

val = f2([0.1; 2.0], [1.0 2.0; 3.0 4.0])

However, I have seen other sources that suggest that annotating code with type information is the key to performance in Julia. For instance, I’m told that if I preallocate a vector I should always include type information.

I’m sure there’s a lot I’m not fully understanding but If someone could provide some tips or general guidance on these issues, it would be very helpful for beginners like me.

9 posts - 7 participants

Read full topic


Viewing all articles
Browse latest Browse all 2795

Latest Images

Trending Articles



Latest Images