Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performances of Structs vs Classes

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.

like image 300
systemsfault Avatar asked Mar 25 '11 12:03

systemsfault


People also ask

Are structs faster than classes?

So based on the above theory we can say that Struct is faster than Class because: To store class, Apple first finds memory in Heap, then maintain the extra field for RETAIN count. Also, store reference of Heap into Stack. So when it comes to access part, it has to process stack and heap.

Are structs better than classes?

There is no difference between classes and structs. Structs are classes; only default access is flipped from private to public.

Why are structs better than classes?

The only difference between a struct and class in C++ is the default accessibility of member variables and methods. In a struct they are public; in a class they are private.

Are structs faster than classes in C++?

To answer your question, struct is slightly faster.


1 Answers

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++.

like image 143
Alexander Poluektov Avatar answered Sep 20 '22 13:09

Alexander Poluektov