Declaring types: Vector{Union{Int64, Matrix{Int64}}} is much slower than Vector{Any}, why is that?
The following code is different from my declarations. f0 is not declared, f1 is declared ::Vector{Any}, and f2 is declared ::Vector{Union{Int64, Matrix{Int64}}}
function f0(path_info)
trace_iteration = []
count=0
for k in 1:length(path_info)
p_path=path_info[k]
t1::Int64 = p_path[1]
t2::Int64 = p_path[2]
if t1 < 5 && t2 <5
count += 1
end
end
push!(trace_iteration, count)
return trace_iteration
end
function f1(path_info)
trace_iteration = []
count=0
for k in 1:length(path_info)
p_path::Vector{Any}=path_info[k]
t1::Int64 = p_path[1]
t2::Int64 = p_path[2]
if t1 < 5 && t2 <5
count += 1
end
end
push!(trace_iteration, count)
return trace_iteration
end
function f2(path_info)
trace_iteration = []
count=0
for k in 1:length(path_info)
p_path::Vector{Union{Int64, Matrix{Int64}}}=path_info[k]
t1::Int64 = p_path[1]
t2::Int64 = p_path[2]
if t1 < 5 && t2 <5
count += 1
end
end
push!(trace_iteration, count)
return trace_iteration
end
path_info0=[[rand(1:10),rand(1:10),rand(1:10),rand(1:10),rand(Int,2,2)] for i in 1:1000000]
@btime f0(path_info0) #16ms
@btime f1(path_info0) #15.6ms
@btime f2(path_info0) # 243ms
It can be seen that declaring a union type will be 10 times slower. Is there any way to declare the variable to speed up the function?
versioninfo()
Julia Version 1.10.0
Commit 3120989f39 (2023-12-25 18:01 UTC)
Build Info:
Official https://julialang.org/ release
Platform Info:
OS: Windows (x86_64-w64-mingw32)
CPU: 20 × 12th Gen Intel(R) Core(TM) i7-12700
WORD_SIZE: 64
LIBM: libopenlibm
LLVM: libLLVM-15.0.7 (ORCJIT, alderlake)
Threads: 1 on 20 virtual cores
Environment:
JULIA_NUM_THREADS1 = 1
JULIA_PKG_SERVER = https://mirrors.bfsu.edu.cn/julia
JULIA_PYTHONCALL_EXE = @PyCall
JULIA_EDITOR = code
JULIA_NUM_THREADS =