I have a two-argument function, for which I want to cache the results. Currently I use a Dict to store the previous results. The performance is OK, but profiling said that a lot of time is taken by finding the index.
dict_index = Base.ht_keyindex(S.fval, (i,j))
if dict_index >= 0
return S.fval.vals[dict_index]
end
Depending on the data an array with findfirst or, better if possible, searchsortedfirst may be faster.
Also be user to use a type-stable dict or array.
Yeah, just tested it here, and it seems that searchsortedfirst is never faster than a getindex from a dict. They are similar at <100 elements only. So that’s not an option.
You need to show more code for people to be able to help you. What is S? What is S.fval? What is S.fval.vals? Is your Dict properly typed? Are you digging into the internals of Dict, because this doesn’t look like Julia code I’m familiar with.
struct SMat{fvalT}
....
fval::Dict{NTuple, fvalT}
function SMat(....)
new(..., Dict{NTuple{2, Int}, fvalT}())
end
end
I believe the Dict fval is properly typed, which stores the values of the matrix.
function getindex(S::SMat, i::Int, j::Int)
return get!(S.fval, (i,j)) do
# Slow path
end
end
The function I want to cache is this getindex. Thanks to @Dan, it is quite elegant now.
Profiling shows that get! is hit many times and it calls ht_keyindex2!. To be honest, the Dict is already quite fast. Maybe I should consider other ways to cache the results?