Faken
Faken

Reputation: 11822

Are there any performance penalties when using nested structures?

Are there any performance penalties when 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

Upvotes: 5

Views: 2140

Answers (4)

dsimcha
dsimcha

Reputation: 68740

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
}

Upvotes: 1

EboMike
EboMike

Reputation: 77732

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.

Upvotes: 5

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

Short answer: No.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190925

There shouldn't be any performance or memory penalties. They are just syntactic sugar to make things easier for the programmer.

Upvotes: 1

Related Questions