This question is generally regarding when it is a good idea to store quantities derived from member data in, say, std::vector
s that will be repeatedly computed/accessed in various methods, but I will attempt to illustrate it within a specific context.
Suppose that I have two classes as minimally defined below. The Configuration
class has multiple additional methods that need to access quantities derived from member data of Particle
objects. For instance, in a simulation, the particle positions will be updated quite frequently, and these additional methods will need the separation vector between particles, computed with the computeSeparationVector(...)
method below.
Is it better in terms of performance/efficiency to repeatedly call this function from the various methods that need this information, or is it more performant to compute this data once for each update step and store it in, say, std::vector<std::valarray<double>> separationVectors
? If it's the latter, any suggestions on recommended ways to store such data would be greatly appreciated.
This is obviously a simplistic example, but deciding whether or not to store computed/derived data in member data containers is something I'm currently grappling with. Thanks!
#include <valarray>
#include <vector>
class Particle {
public:
Particle(long index, double x, double y, double rad):
particleIndex(index),
particleRadius(rad),
xCoord(x),
yCoord(y)
{ }
const long particleIndex;
double particleRadius;
std::valarray<double> getCoords() {
return {xCoord, yCoord};
}
private:
double xCoord;
double yCoord;
};
class Configuration {
public:
std::vector<Particle> particles;
Particle getParticle(long particleIndex) const {
return particles[particleIndex];
}
void addParticle(const Particle& particle) {
particles.emplace_back(particle);
}
std::valarray<double> computeSeparationVector(long particle1Index, long particle2Index) const {
return getParticle(particle1Index).getCoords() - getParticle(particle2Index).getCoords();
}
};