Pigna
Pigna

Reputation: 2924

How often is type declaration necessary in Julia for optimal performance?

I have started translating from python a game engine for a boardgame I have invented. I know that the example I am going to show is pretty meaningless, there is no real need to optimize it, but I would like to get this right before dealing with the heavy functions.

function howMany()::Int8
    pieces::Int8 = 0
    while pieces > 8 || pieces < 4
        try
            print("How many pieces are we going to play with (min 4, max 8)? ")
            pieces = parse(Int8, readline(STDIN))
        catch
            println("It must be an integer number between 4 and 8!")
        end
    end
    return pieces
end

function main()
    pieces::Int8 = howMany()
    #println(pieces, typeof(pieces))
end

main()

Is it necessary to declare Int8 4 times (3 declaration + parse parameter)? When can I avoid specifying Int8 without having any performance trade off?

Upvotes: 2

Views: 188

Answers (1)

Dan Getz
Dan Getz

Reputation: 18227

Twice in the following which avoids expensive try-catch:

function howMany()
    while true
        print("How many pieces are we going to play with (min 4, max 8)? ")
        pieces = get(tryparse(Int8, readline(STDIN)), Int8(0))
        4 <= pieces <= 8 && return pieces
        println("It must be an integer number between 4 and 8!")
    end
end

function main()
    pieces = howMany()
    println(pieces, typeof(pieces))
end

main()

Uses nice short-cuts such as:

  • get with default

  • short-circuit && instead of bulkier if ... end.

And it is code-stable as @code_warntype howMany() shows.

Upvotes: 4

Related Questions