Reputation: 165
I'm rather new to Julia (from Python3 experience) and i'm trying to rewrite my code to make it run faster .. performance seems to be an important issue in Julia code, esp. with scripts which calculate by recursions, like my (simple) chess engine, examining a move tree ..
i found this SO question :
How to correctly define and use global variables in the module in Julia? How to correctly define and use global variables in the module in Julia?
here, the use of Ref()
is shown:
const x = Ref(0)
then use x
by writing x[]
: this way x
seems to be considered a global variable, accessable in every function, and my current script relies mainly on this approach : no need to define variables as global when using them inside a function, and no need to pass data by parameters.
Btw. Ref(0) defines an Integer, define a list by Ref([]), etc.
indeed, this approach works, but my final script seems even SLOWER than its Python original - of which i did a rewrite .. and running the original Python script using PyPy even outperformes Python about 4 times !
is the use of Ref()
slowing down the whole process ?
am i missing something basic ?
[ i'm also reading https://viralinstruction.com/posts/optimise/ ]
Upvotes: 0
Views: 262
Reputation: 42214
To be precise. Consider this code in Julia 1.9.
const a1 = 5 # fastest type stable because of const
const a2::Int = 5 # fastest
const a3 = Ref(5) # 2x slower, mutable
a4::Int = 5 # 2x slower
a5 = 5 # bad practice
Now try to access those globals (the results discussed above):
julia> @btime +(a1, 1);
1.900 ns (0 allocations: 0 bytes)
julia> @btime +(a2, 1);
1.900 ns (0 allocations: 0 bytes)
julia> @btime +(a3[], 1)
3.600 ns (0 allocations: 0 bytes)
julia> @btime +(a4, 1);
3.700 ns (0 allocations: 0 bytes)
julia> @btime +(a5, 1);
31.446 ns (0 allocations: 0 bytes)
Upvotes: 3
Reputation: 6388
It's hard to know without more code, but the problem likely isn't in the code you've shared. That said, as of julia 1.9, you can instead write x::Int = 0
rather than the previously necessary Ref
trick to make globals fast.
Upvotes: 3