C++: Performance impact of BIG classes (with a lot of code)

前端 未结 9 1979
执念已碎
执念已碎 2021-01-17 15:08

I wonder if and how writing \"almighty\" classes in c++ actually impacts performance.

If I have for example, a class Point, with only uint x

相关标签:
9条回答
  • 2021-01-17 15:34

    First: do not optimize prematurely. Second: clean code is easier to maintain than optimized code.

    Methods for classes have the hidden this pointer, but you should not worry about it. Most of the time the compiler tries to pass it via register.

    Inheritance and virtual function introduce indirections in the appropriate calls (inheritance = constructor / destructor call, virual function - every function call of this function).

    Short:

    • Objects you don't create/destroy often can have virtual methods, inheritance and so on as long as it benefits the design.
    • Objects you create/destroy often should be small (few data members) and should not have many virtual methods (best would be none at all - performance wise).
    • try to inline small methods/constructor. This will reduce the overhead.
    • Go for a clean design and refactor if you don't reach the desired performance.

    There is a different discussion about classes having large or small interfaces (for example in one of Scott Meyers (More) Effective C++ Books - he opts for minimal interface). But this has nothing to do with performance.

    0 讨论(0)
  • 2021-01-17 15:36

    If you are truly worried, you can tell your compiler to inline the constructors. This optimization step should leave you with clean code and clean execution.

    0 讨论(0)
  • 2021-01-17 15:49

    I agree with the above comments wrt:performance and class layout, and would like to add a comment not yet stated about design.

    It feels to me like you're over-using your Point class beyond it's real Design scope. Sure, it can be used that way but should it?

    In past work in computer games I've often been faced by similar situations, and usually the best end result has been that when doing specialized processing (e.g. image processing) having a specialized code set for that which work on differently laid-out buffers has been more efficient.

    This also allows you to performance optimize for the case that matters, in a more clean way, without making base code less maintainable.

    In theory, I'm sure that there is a crafty way of using a complex combination of template code, concrete class design, etc., and getting nearly the same run-time efficiency ... but I am usually unwilling to make the complexity-of-implementation trade.

    0 讨论(0)
提交回复
热议问题