Hacker News new | ask | show | jobs
by layer8 396 days ago
Operating systems usually initialize new memory pages to zero by default, for security reasons, so that a process can’t read another process’s old data. So this gives you zero-initialization “for free” in many cases. Even when the in-process allocator has to zero out a memory block upon allocation, this is generally more efficient than the corresponding custom data-type-specific default initialization.

If you have a sparse array of values (it might be structs), then you can use a zero value to mark an entry that isn’t currently in use, without the overhead of having to (re-)initialize the whole array up-front. In particular if it’s only one byte per array element that would need to be initialized as a marker, but the compiler would force you to initialize the complete array elements.

Similarly, there are often cases where a significant part of a struct typically remains set to its default values. If those are zero, which is commonly the case (or commonly can be made the case), then you can save a significant amount of extra write operations.

Furthermore, it also allows flexibility with algorithms that lazy-initialize the memory. An algorithm may be guaranteed to always end up initializing all of its memory, but the compiler would have no chance to determine this statically. So you’d have to perform a dummy initialization up-front just to silence the compiler.