In an earlier blog post, I reported that the memory usage of a small byte array in Java (e.g., an array containing 4 bytes) was about 24 bytes. In other words: allocating small blocks of memory has substantial overhead.
What happens in C++?
To find out, I can try to allocate one million 4-byte arrays and look at the total memory usage of the process. Of course, the memory usage of the process will include some overhead unrelated to the 4-byte arrays, but we expect that such overhead will be relatively small.
From my benchmark, I get the following results…
|system||memory usage (in bytes)|
|GCC 8, Linux x86||32 bytes|
|LLVM 14, Apple aarch64||16 bytes|
The results will vary depending on the configuration of your system.
The lesson is that allocating four bytes (new char or malloc(4)) does not use four bytes of memory… it will generally use much more.