Menu

False performance warning with tiny class?

Konstantin
2015-06-30
2015-07-05
  • Konstantin

    Konstantin - 2015-06-30

    In most cases it's quicker to pass const class into function by reference, not by value.
    I.e.
    void foo1(const A& a);
    is quicker than
    void foo2(const A a);
    Cppcheck shows these performance hints.

    But sometimes, when class is tiny, it's quicker to pass class by value.
    I.e.:
    class A {
    int x;
    };

    In foo1(...) pointer is copied.
    Each access to variable x means (hidden) dereverence of variable a.
    In foo2(...) same four bytes are copied, do it's not slower.
    Variable x is placed into local stack. It's memory address is known.
    In this case there are no dereferences. So foo2(...) is quicker than foo1(...).
    But cppcheck shows that foo1(...) is better.

     

    Last edit: Konstantin 2015-06-30
  • Daniel Marjamäki

    ok .. can you define "tiny"?

     
    • Konstantin

      Konstantin - 2015-07-05

      Size of the class is less then size of pointer to that class.

      In this case copy of data in variable of that class is not longer than copy of pointer to variable of that class, but access is faster.

       

      Last edit: Konstantin 2015-07-05
    • Konstantin

      Konstantin - 2015-07-05

      New assumption:
      Copy of a variable of class A if no longer than pass it by reference if:
      1. Size of class A if less or equal than size of pointer to class A.
      2. Class A and all it's subclasses use default create-by-copy consructor.

      Previous definition of tiny class (size of the class is less then size of pointer to that class) is not good.

      Example 1:

      class A {
      int x;
      A(const A& a) {x = a.x; sleep(10000000);}
      };

      Example 2:

      class A {
      B b;
      };

      class B : public C {
      };

      class C {
      int x;
      C(const C& c) {x = c.x; sleep(10000000);}
      }

      This new assumption is hard ro realise. But classes like next are very popular:

      struct Rect {
      short X;
      short Y;
      };

      Copy a variable of class Rect instead of pass it by reference will improve performance.

       

      Last edit: Konstantin 2015-07-05
  • Daniel Marjamäki

    sounds ok.

    When --platform is not used we don't know the type sizes. but we could try to skip warnings then when the struct "looks" like a "tiny" class.

    can you report a ticket in our issue tracker so we don't forget this?
    http://trac.cppcheck.net/

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.