Are there any performance penalties whe开发者_Go百科n I use multiple nested structures/classes (kinda like using muti dimension heap arrays) or is it just an organizational feature of the language to make it easier to keep track of data and the compiler doesn't actually see any difference?
Thanks
Not really. Classes/structs are just defining offsets into memory, so if you have a class within a class within a class, the compiler just adds up the offsets.
Performance comes into play once you have pointers (each pointer dereference is a memory read and potential L2 cache miss) or virtual functions (very bad, especially on older CPUs).
EDIT: One thing I should note though - if you're developing an application where performance is not absolutely crucial, focus on good class design rather than performance. While things like L2 cache misses make a big difference when you're writing something that needs to run at 60fps, it is of little relevance in a normal desktop application.
There shouldn't be any performance or memory penalties. They are just syntactic sugar to make things easier for the programmer.
Short answer: No.
Mostly no, as others have mentioned. However, there's a small exception: Putting structs within structs can cause a small memory usage penalty due to alignment issues, relative to the same primitives being put directly in a single struct. This can in theory cost cache misses, which hurt performance. For example:
#include <iostream>
using namespace std; // So sue me
struct A {
double d;
int i;
};
struct B {
int j;
int k;
int l;
};
struct AB {
A a;
B b;
};
struct C {
double d;
int i;
int j;
int k;
int l;
};
int main() {
cout << sizeof(AB) << endl; // 32
cout << sizeof(C) << endl; // 24
}
精彩评论