Skip to content

Instantly share code, notes, and snippets.

@oheil
Last active December 25, 2023 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oheil/d666bdc727902052905c400b5b14ff6d to your computer and use it in GitHub Desktop.
Save oheil/d666bdc727902052905c400b5b14ff6d to your computer and use it in GitHub Desktop.
Implementing global state without globals
using BenchmarkTools
N=100_000
# With a let block:
let state = Ref{Bool}(false)
global setLastShowHidden, getLastShowHidden
function setLastShowHidden(b::Bool)
state[] = b
end
function getLastShowHidden()
state[]
end
end
function bLet(n)
for _ in 1:n
if getLastShowHidden()
setLastShowHidden(false)
else
setLastShowHidden(true)
end
end
end
# With a functor:
mutable struct ShowHidden
last::Bool
end
function (sh::ShowHidden)(b::Bool)
sh.last = b
end
function (sh::ShowHidden)()
sh.last
end
const lastShowHidden = ShowHidden(false)
function bFunctor(n)
for _ in 1:n
if lastShowHidden()
lastShowHidden(false)
else
lastShowHidden(true)
end
end
end
# Benchmarks:
@btime bLet($N)
# 360.952 ns (0 allocations: 0 bytes)
@btime bFunctor($N)
# 305.837 ns (0 allocations: 0 bytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment