Elixir Binary Memory
Binary memory is how text and bytes are stored as a binary value. A binary holds bytes, and its size counts those bytes.
Byte size counts bytes
The word hello takes five bytes. An empty binary takes none.
IO.inspect(byte_size("hello"))
IO.inspect(byte_size(""))One character can take more than one byte
The accented e in héllo takes two bytes. The character count stays five.
IO.inspect(byte_size("héllo"))
IO.inspect(String.length("héllo"))A slice is smaller than its source
A large binary built from repeated text has two thousand bytes. Its first two bytes form a tiny piece.
big = String.duplicate("ab", 1000)
IO.inspect(byte_size(big))
IO.inspect(binary_part(big, 0, 2))
IO.inspect(byte_size(binary_part(big, 0, 2)))Example
greeting = "hello" <> " world"
IO.inspect(byte_size(greeting))
IO.inspect(binary_part(greeting, 0, 5))
IO.inspect(byte_size(binary_part(greeting, 0, 5)))
IO.inspect(byte_size("héllo"))Key points
- Binary: a binary is a sequence of bytes that holds text or raw data.
- Byte size: byte_size counts the bytes in a binary, not the characters in it.
- Character count: String.length counts characters, so it can differ from the byte count for non-ASCII text.
- Empty binary: an empty binary has a byte size of 0.
- Slice: binary_part takes a piece of a binary from a start position for a length.
- Use byte_size to check the size of a binary before you store or send it.
In this example, two pieces are joined into one greeting, then the greeting byte size is printed, then its first five bytes are printed, then the byte size of that piece is printed, and finally the byte size of an accented word is printed for contrast.
Note
a small piece taken from a large binary can keep the large binary alive.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is byte_size("héllo")?