Skip to content

Commit

Permalink
Merge pull request #5 from oxinabox/ox/microopt
Browse files Browse the repository at this point in the history
Careful microoptimisations for 2x performance improvement
  • Loading branch information
oxinabox authored Jan 14, 2018
2 parents 05e2894 + 95b3916 commit 90c0c87
Showing 1 changed file with 24 additions and 17 deletions.
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

0 comments on commit 90c0c87

Please sign in to comment.