Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Careful microoptimisations for 2x performance improvement #5

Merged
merged 5 commits into from
Jan 14, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 24 additions & 17 deletions src/corefunctionality.jl
Original file line number Diff line number Diff line change
@@ -1,22 +1,29 @@

const pool = WeakKeyDict{String, Void}()

function intern!(wkd::WeakKeyDict{K}, key)::K where K
kk = convert(K, key)
kwr = WeakRef(kk)
lock(wkd) do
found_key = getkey(wkd.ht, kwr, Base.secret_table_token)
found = !(found_key === Base.secret_table_token)

if found
return found_key.value
else
# Not found, so add it,
# and mark it as a reference we track to delete!
finalizer(kk, wkd.finalizer)
wkd.ht[kwr]=nothing
return kk
end
# This forces the type to be inferred (I don't know that the @noinline is reqired or even good)
@noinline getvalue(::Type{K}, wk) where K = wk.value::K


# NOTE: This code is carefully optimised. Do not tweak it (for readability or otherwise) without benchmarking
@inline function intern!(wkd::WeakKeyDict{K}, key)::K where K
kk::K = convert(K, key)

lock(wkd.lock)
# hand positioning the locks and unlocks (rather than do block or try finally, seems to be faster)
index = Base.ht_keyindex2(wkd.ht, kk) # returns index if present, or -index if not
# note hash of weakref is equal to the hash of value, so avoid constructing it if not required
if index > 0
# found it
@inbounds found_key = wkd.ht.keys[index]
unlock(wkd.lock)
return getvalue(K, found_key) # return the strong ref
else
# Not found, so add it,
# and mark it as a reference we track to delete!
finalizer(kk, wkd.finalizer) # finalizer is set on the strong ref
@inbounds Base._setindex!(wkd.ht, nothing, WeakRef(kk), -index)
unlock(wkd.lock)
return kk # Return the strong ref
end
end

Expand Down