33

I wonder if there are performance comparisons of classes and C style structs in C++ with g++ -O3 option. Is there any benchmark or comparison about this. I've always thought C++ classes as heavier and possibly slower as well than the structs (compile time isn't very important for me, run time is more crucial). I'm going to implement a B-tree, should I implement it with classes or with structs for the sake of performance.

systemsfault
  • 15,207
  • 12
  • 59
  • 66
  • 5
    Which of your exact twins do you love the most? – David Rodríguez - dribeas Mar 25 '11 at 13:57
  • 2
    Actually I've never used advanced features of C++ structs, I've always used them as a data-container for public data just like a C struct. When I need complex functionalities like inheritance, polymorphism etc, I prefer to use classes. So this is not a love and hate relationship – systemsfault Mar 25 '11 at 14:18

7 Answers7

59

On runtime level there is no difference between structs and classes in C++ at all. So it doesn't make any performance difference whether you use struct A or class A in your code.

Other thing, is using some features -- like, constructors, destructors and virtual functions, -- could have some performance penalties (but if you use them you probably need them anyway). But you can with equal success use them both inside your class or struct.

In this document you can read about other performance-related subtleties of C++.

Alexander Poluektov
  • 7,844
  • 1
  • 28
  • 32
  • Do you know any document or benchmarks about their memory consumption: structs vs classes. – systemsfault Mar 25 '11 at 13:04
  • 11
    Once again: no difference between structs and classes at runtime level -- both performance and memory consumption. You can think about them as different keywords for the same thing which only differs in default access to members and default inheritance mode (and you cannot use 'struct' inside template parameter list, but your question is not about it, right?) – Alexander Poluektov Mar 25 '11 at 13:07
  • Would a struct in C be faster than a struct in C++? – Nanashi No Gombe Jul 17 '20 at 09:48
26

In C++, struct is syntactic sugar for classes whose members are public by default.

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • 12
    Or looking at it another way, `struct` is the syntax which is backward-compatible to C, and `class` is the more OOP-like syntactic sugar for classes whose members are private by default... – Steve Jessop Mar 25 '11 at 13:08
  • 9
    I'd like to give this answer +1.000.000 (only slightly exagerating ;) ) if I could, since the misconception that leads to the original question is so widespread. so everybody repeat after me: "**`struct` and `class` are equivalent** (except for default access)" – Fabio Fracassi Mar 25 '11 at 14:06
  • 2
    I abstain from sugar. can I have a sugar free struct? – Simple Fellow Aug 31 '16 at 20:23
  • I wonder how the language's evolution would have been affected if "struct" syntax were limited to PODS, and if the guarantees that apply to PODS were only applicable to types declared "struct"? Adding a new keyword which basically means the same thing as a combination of `struct` and `private` seems rather wasteful. – supercat Aug 30 '18 at 16:01
12

My honest opinion...don't worry about performance until it actually shows itself to be a problem, then profile your code. Premature optimization is the root of all evil. But, as others have said, there is no difference between a struct and class in C++ at runtime.

Mark Loeser
  • 17,657
  • 2
  • 26
  • 34
3

Focus on creating an efficient data structure and efficient logic to manipulate the data structure. C++ classes are not inherently slower than C-style structs, so don't let that limit your design.

gregg
  • 1,027
  • 5
  • 6
  • 6
    He clearly asked about the differences between classes and structs and not about tips regarding software design. – Tara Jun 12 '13 at 14:08
2

AFAIK, from a performance point of view, they are equivalent in C++.

Their difference is synctatic sugar like struct members are public by default, for example.

my2c

neuro
  • 14,948
  • 3
  • 36
  • 59
0

Just do an experiment, people!

Here is the code for the experiment I designed:

#include <iostream>
#include <string>
#include <ctime>
using namespace std;
class foo {
  public:
    void foobar(int k) {
      for (k; k > 0; k--) {
        cout << k << endl;
      }
    }
    void initialize() {
      accessor = "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdf";
    }
    string accessor;
};
struct bar {
  public:
    void foobar(int k) {
      for (k; k > 0; k--) {
        cout << k << endl;
      }
    }
    void initialize() {
      accessor = "asdfasdfasdfasdfasdfasdfasdfasdfasdfasdf";
    }
    string accessor;
};

int main() {
  clock_t timer1 = clock();
  for (int j = 0; j < 200; j++) {
    foo f;
    f.initialize();
    f.foobar(7);
    cout << f.accessor << endl;
  }
  clock_t classstuff = clock();
  clock_t timer2 = clock();
  for (int j = 0; j < 200; j++) {
    bar b;
    b.initialize();
    b.foobar(7);
    cout << b.accessor << endl;
  }
  clock_t structstuff = clock();
  cout << "struct took " << structstuff-timer2 << endl;
  cout << "class took " << classstuff-timer1 << endl;
  return 0;
}

On my computer, struct took 1286 clock ticks, and class took 1450 clock ticks. To answer your question, struct is slightly faster. However, that shouldn't matter, because computers are so fast these days.

ndrewxie
  • 172
  • 3
  • 10
  • 2
    Actually, this test might not be optimal, the first test will tend to take longer times than the second since the processor will have to prepare to execute it. It would be better to run both loops several times before taking the measures and avoid using IO since it hinders the measure precision considerably. I made a few changes on your test and my results indicated both have the same performance, sometimes one goes slightly faster other times the other one, i.e.: (class: 1116, 530, 523, 507) (struct: 1087, 498, 541, 543). – VinGarcia May 29 '17 at 14:07
  • My original code was to do that, but I deleted it by accident, so I just wrote some quick and dirty code to post :) – ndrewxie May 30 '17 at 18:18
-3

well actually structs can be more efficient than classes both in time and memory (e.g arrays of structs vs arrays of objects),

‎‏There is a huge difference in efficiency in some cases. While the overhead of an object might not seem like very much, consider an array of objects and compare it to an array of structs. Assume the data structure contains 16 bytes of data, the array length is 1,000,000, and this is a 32-bit system. For an array of objects the total space usage is: 8 bytes array overhea (4 byte pointer size × ((8 bytes overhead + = 28 MB For an array of structs, the results are dramatically different: 8 bytes array overhea (16 bytes data × 1,00 = 16 MB With a 64-bit process, the object array takes over 40 MB while the struct array still requires only 16 MB.

see this article for details.

AmjadHD
  • 163
  • 6
  • The article has a big C# logo in it, IDK how you missed it, this SO question is about C++ class and structs. – 0xdeadbeef Jul 22 '23 at 14:26