Last active
December 25, 2023 14:37
-
-
Save oheil/d666bdc727902052905c400b5b14ff6d to your computer and use it in GitHub Desktop.
Implementing global state without globals
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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