Julia Memory Layout
Memory layout is how values sit in memory. Size and order decide how much room a value needs and where each part sits.
Sizes are counted in bytes
A 64-bit number takes 8 bytes. A smaller integer takes fewer.
println(sizeof(Int64))
println(sizeof(Float64))
println(sizeof(Int8))Padding adds unused bytes inside a struct
Two small bytes fit in 2 bytes. A small byte beside a large number needs padding.
struct PairBytes
a::Int8
b::Int8
end
struct Mixed
a::Int8
b::Int64
end
println(sizeof(PairBytes(1, 2)))
println(sizeof(Mixed(1, 2)))Arrays list columns first
A matrix lists down its first column first. The vector form shows that order.
m = [10 20; 30 40]
println(vec(m))
println(m[1, 2])Example
struct Tile
row::Int64
col::Int64
end
println(sizeof(Tile(3, 4)))
grid = [1 2 3; 4 5 6]
println(vec(grid))
println(length(vec(grid)))Key points
- Size: sizeof reports the size of a value in bytes.
- Padding: a struct size can exceed the sum of its field sizes because of unused bytes inside it.
- Column order: Julia arrays store columns first, so a matrix lists down its first column before its second.
- Field order: fields sit in the order they are declared in a struct.
- Length: length counts entries, not bytes, so it cannot tell you a size in bytes.
In this example, a tile with two 64-bit fields takes 16 bytes. A two row grid is then turned into a vector. The vector lists the first column before the second, and its length is 6.
Note
sizeof of a type and sizeof of a value of that type give the same number.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
What does sizeof report for a value?