4 ms·
It's been a long time since I've done any speed optimisation stuff / assembly coding but one of the quirks of REP STOS/MOVS I recall is that it is very sensitiv
by robert_tweed 12y ago
It's been a long time since I've done any speed optimisation stuff / assembly coding but one of the quirks of REP STOS/MOVS I recall is that it is very sensitive to memory alignment. I.e., if you try to do a MOVSD without using a 4-byte aligned base address, it will be very slow; similarly a MOVSQ must be 8-byte aligned. I wonder if this is just a case of someone having benchmarked a naive implementation without taking alignment into account? As other commenters have noted, loop unrolling isn't a great idea on a modern CPU and it certainly wouldn't have got anywhere close to the speed of REP on an older CPU when I was doing this kind of thing.
The right way to fix alignment is to have some MOVSB/MOVSW instructions at the start and jump over the correct number based on the difference between your actual base address and the offset you want, then do the rest with REP. I haven't tried to pick apart the source in detail but it looks like they are just doing a naive REP.
Of course it's possible that this is only used in arrays that are known to be 4/8 byte aligned anyway, in which case this comment is irrelevant. However it's a very surprising result that the in-built and widely used instruction provided by the CPU for doing exactly this operation is slower than the dumb loop unrolling approach, even with all the instruction cache and memory bandwidth problems it introduces. Odd results like that usually point to programmer error rather than surprising CPU behaviour (although if that were always the case, Michael Abrash's books would be a lot less interesting).