Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is filling memory with non zero values slower than filling it with zeros?

I'm not very expert on how processors work, but one might imagine that it was easier to set chunks of memory to zero than non zero values and so it may be marginally faster.

like image 201
Mick Avatar asked Mar 10 '10 17:03

Mick


2 Answers

I think the only difference would be in setting up the register that has the value to store to memory. Some processors have a register that's fixed at zero (ia64 for example). Even so, whatever minuscule overhead there might be for setting up a register will be monstrously dwarfed by the writing to memory.

As far as the time to actually write to the memory - that'll be clocked the same on all architectures I'm familiar with.

like image 100
Michael Burr Avatar answered Oct 30 '22 11:10

Michael Burr


Theoretically, it it might be indeed faster.

Firstly, the hardware platform might offer a dedicated CPU instruction(s) that sets memory to zero.

Secondly, setting memory to zero specifically might be supported by OS/hardware as a lazy operation, i.e. the act of actually setting memory to zero doesn't really do anything besides simply marking this memory region for zeroing on the first read. (Of course, something like that is only possible with memory regions managed at OS/hardware level).

The latter actually is one of the reasons the calloc function exists: on some platforms it can be implemented significantly more efficiently than a mere malloc followed by a memset to zero. On such platforms the effect will be thremendously large, not "marginal".

like image 24
AnT Avatar answered Oct 30 '22 13:10

AnT