C++ Jumbling classes to enhance locality of reference?

100 views Asked by At

Should we organize classes based on locality rather than conceptually?

Hypothetically, suppose we write a program to simulate a real-world environment which has three objects: a car, road and tree. Conventional OOP design suggests to conceptually separate these 3 separate classes.

But suppose the car and road objects do millions of calculations among their class member data and methods. Could we improve performance by jumbling the Car and Road into a CarRoad class due to locality of reference? Or if that example is too absurd, if we had another separate Wheel class, which is closely related to a Car, should we jumble the Car and Wheel classes together if their class members interact very frequently?

2

There are 2 answers

0
glaze On

I wouldn't decide that unless I really profile two different version and compare the performance.

Otherwise I'd like to try a couple of things like, 1. Would it make more sense if one of the other class has template parameter and pass it, instantiating it in compile time. 2. Put one class in another class but inline all of its methods, and also force it(there's compiler flag /attribute to actually force it..) to see if the generated binary has somewhat different locality.

Just random idea..

1
ravi On

Whether Car and Road could be merged into single class depends on the system you are trying to model. Never try to merge just for getting good locality of reference ( although your idea is superfloues ).

Locality of reference comes into picture when you instantiate the objects of this class. Let me show you through a simple example:-

Suppose we have to choose either vector OR map among the containers.

1) map offers poor locality of reference with respect to vector :-

map is internally implemented in terms of balanced binary tree. So, that means map along with storing data also stores two pointers i.e left subtree and tight subtree ( there could also be pointer to parent ). That means it requires more space per element to store same data as in let's say vector. So, in this case less data would fit into single page of virtual memory.

2) vector offers good locality of reference :-

Since there is no headache of storing pointers along with data in vector, it can store more elements per page compared to map. And that why vector is better than map in terms of locality of reference.