Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Branch prediction between objects of same class

I'm optimizing a program, and trying to avoid branch misprediction. I have two objects of a class. In the class's primary function there are several if branches. Each object takes a different direction on each of those branches, and they each run the function one after another. My questions:

Since they're members of the same class, and are therefore sharing that function, are they also sharing the same branch prediction? Essentially, am I making the system go TFTFTFTF...

Or, since they're their own objects do they have their own branch predictions and therefore maintaining consistent predictions (TTTTTTT... and FFFFFFFF...)

like image 987
Hanley Avatar asked Jan 23 '26 07:01

Hanley


2 Answers

Yes, the method is shared between instances of a class.

It means, as well, that the predictions are shared.

However, there is more to branch prediction than the "last" time. The processor will remember some of the last results and identify "easy" (cyclic) patterns. Therefore, if you constantly swap between your two objects and the pattern ends up TFTFTFTFTF then the processor will correctly guess that the next result will be a T.

From a semantic point of view, however, did you thought about using a base class and two different derived classes (+ the usual virtual mechanism) ?

like image 120
Matthieu M. Avatar answered Jan 24 '26 20:01

Matthieu M.


Don't bother about such low-level details like branch prediction (it will vary from one model of a processor to the next). Leave that optimization to the compiler (and it is probably good enough).

If you want to improve your application, work more on the algorithms themselves. And use profiling & measurements. Don't forget that premature optimization is evil.

like image 31
Basile Starynkevitch Avatar answered Jan 24 '26 22:01

Basile Starynkevitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!