- Suppose that it is only necessary to bind a value to a certain
datamember of a certain object when bState is true. When bState
is false, it is not necessary, but it does not hinder either.
Which of the following pieces of code would be more efficient, and why?
(EDIT: updated, state is now a member of the object)
const int x;
int i;
int iToBind;
Classname pObject[x];
for (; i < x; ++i) {
if (pObject[i].bState) {
pObject[i].somedatamember = iToBind;
}
}
Versus:
for (; i < x; ++i) {
pObject[i].somedatamember = iToBind;
}
I would say the latter is definitely quicker. The first version has bidirectional memory access, the latter has unidirectional memory access.
In this version:
there is a stall during the
ifstatement as the CPU must wait for the data to be read from memory. The speed the memory is read is dependent on where the data is residing. The further from the CPU the longer it takes: L1 (fastest), L2, L3, Ram, Disk (slowest).In this version:
there are only writes to memory. Writes to memory do not stall the CPU.
As well as the memory access times, the latter loop has no conditional jump inside the loop. Conditional loops are a significant overhead, especially if the taken/not taken decision is effectively random.