0

I have an engine and if I want to use the 3d system I always have to pass a pointer to any mesh renderer. If I would make the 3d system static then I just could use them. But the 3d system is big with lots of stuff and resources. I know static fields stay in memory until the end but the graphics system is used all the time. So is it bad for performance to declare the 3d system as a static field in the engine core?

closed as too broad by gnat, Greg Burghardt, 17 of 26, Doc Brown, Jörg W Mittag Nov 16 '18 at 14:25

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

5

Performance-wise, there is not going to be a big difference. However:

  • Prefer explicit interfaces that make their dependencies obvious. So pass your objects around as arguments, even when they were allocated with static storage duration.

  • Avoid static objects because the initialization and destruction of these objects is very complex. For example, the order of initialization may be undefined. I've dealt with lots of hard to reproduce bugs because of this. It could still make sense to have a static unique_ptr<SomeComplexObject> that you assign during application initialization (e.g. in your main()), but that has negligible value over passing a reference around.

  • In extremely performance critical sections you may want to avoid indirection from passing a reference around or from having a global variable that is a pointer. This pointer indirection might also prevent some optimizations. However, these differences will likely only be about cache effects or single-cycle performance differences, so don't think about compromising your design for performance without profiling data to back this decision up.

    Thinking more about this, I would expect the biggest difference to be the overhead from passing an extra argument to many functions. This could cause a calling convention to write arguments to the stack instead of only using registers. But if you want to avoid that, writing inlineable code will be more helpful than choosing a problematic design.

In most cases, choosing a sensible design is more important than going after micro-optimizations like this. The biggest performance wins usually come from avoiding work entirely, and not from doing the same work faster. A clean design will make it easier for you to spot opportunities to avoid unnecessary work, whereas such changes might be very difficult in highly “optimized” code. Making dependencies explicit tends to be part of a clean design.

Not the answer you're looking for? Browse other questions tagged or ask your own question.