Does defining the type of variables give more speed?

Does defining the type of variables give more speed?

If I have a generic Dict () and replace it with a Dict with string keys and array elements as values, should I expect a performance improvement? or, when Julia compiles, understanding the type required by the code, then afterwards is it indifferent to have typed or not?

I ask it because it seems to me that in PHP7, defining the type of variables did not bring more speed, but only more maintainability of the code (as long as you don’t remember me badly).

Many thanks for reply.

I ask to understand this: I jot down the code in julia without worrying too much about the type of variables, lists or dictionaries that are … ok … then I think, now I put the right types, so I speed it up. Is this thought correct?

It depends. For you Dict example, it should improve the speed. In general, containers with concrete types, e.g. Vector{Int}, are faster than the ones of abstract types, e.g. Vector{Integer}. With concrete types Julia will know what it gets out and can specialize the code, otherwise, it has to do generic code. Have a look at the “Performance Tips” in the manual.

Also, PHP is probably quite different as it is interpreted whereas Julia is (partially) compiled. So you’re mental model will need to adjust.

1 Like

you can gain something by specializing, try it out:

using BenchmarkTools

d1 = Dict()
d2 = Dict{Char, Int}()

function f1(d, x::Int)
	d[convert(Char, x)] = x
end

julia> @benchmark for i = 48:128
           f1(d1, i)
       end
BenchmarkTools.Trial: 
  memory estimate:  16 bytes
  allocs estimate:  1
  --------------
  minimum time:     3.489 μs (0.00% GC)
  median time:      3.517 μs (0.00% GC)
  mean time:        3.556 μs (0.00% GC)
  maximum time:     11.359 μs (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     8

julia> @benchmark for i = 48:128
           f1(d2, i)
       end
BenchmarkTools.Trial: 
  memory estimate:  0 bytes
  allocs estimate:  0
  --------------
  minimum time:     2.209 μs (0.00% GC)
  median time:      2.218 μs (0.00% GC)
  mean time:        2.272 μs (0.00% GC)
  maximum time:     8.722 μs (0.00% GC)
  --------------
  samples:          10000
  evals/sample:     9