Skip to content

Instantly share code, notes, and snippets.

@bchaber
Last active June 21, 2022 20:41
Show Gist options
  • Save bchaber/c0a584833632934a32ced24ea9369502 to your computer and use it in GitHub Desktop.
Save bchaber/c0a584833632934a32ced24ea9369502 to your computer and use it in GitHub Desktop.
Why const global is better than immutable struct field?
const H = 20
const W = 20
const f = zeros(9, H, W)
const rho = ones(H, W)
struct Lattice
f :: Array{Float64, 3}
end
const lattice = Lattice(f)
function moments1()
lf = lattice.f
let n, m, i
@inbounds for m=1:W, n=1:H
local a = 0.0
for i=1:9 a += lf[i, n, m] end
rho[n, m] = a
end
end
return nothing
end
function moments2()
let n, m, i
@inbounds for m=1:W, n=1:H
local a = 0.0
for i=1:9 a += f[i, n, m] end
rho[n, m] = a
end
end
return nothing
end
using Einsum
function moments3()
lf = lattice.f
@einsum rho[n, m] = lf[i, n, m]
return nothing
end
function moments4()
@einsum rho[n, m] = f[i, n, m]
return nothing
end
using BenchmarkTools
@btime moments1() # 391.292 ns (0 allocations: 0 bytes)
@btime moments2() # 387.315 ns (0 allocations: 0 bytes)
@btime moments3() # 1467. ns (0 allocations: 0 bytes)
@btime moments4() # 387.108 ns (0 allocations: 0 bytes)
const H = 20
const W = 20
const f = zeros(H, W, 9)
const rho = ones(H, W)
struct Lattice
f :: Array{Float64, 3}
end
const lattice = Lattice(f)
function moments1()
lf = lattice.f
let n, m, i
@inbounds for m=1:W, n=1:H
local a = 0.0
for i=1:9 a += lf[n, m, i] end
rho[n, m] = a
end
end
return nothing
end
function moments2()
let n, m, i
@inbounds for m=1:W, n=1:H
local a = 0.0
for i=1:9 a += f[n, m, i] end
rho[n, m] = a
end
end
return nothing
end
using Einsum
function moments3()
lf = lattice.f
@einsum rho[n, m] = lf[n, m, i]
return nothing
end
function moments4()
@einsum rho[n, m] = f[n, m, i]
return nothing
end
using BenchmarkTools
@btime moments1() # 423.995 ns (0 allocations: 0 bytes)
@btime moments2() # 214.657 ns (0 allocations: 0 bytes)
@btime moments3() # 1471. ns (0 allocations: 0 bytes)
@btime moments4() # 214.623 ns (0 allocations: 0 bytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment