Structs insted of classes for Performance
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Apr 20 09:56:59 PDT 2014
My understanding is not perfect. There may be compiler and CPU
optimizations that I am not aware of.
On 04/20/2014 08:03 AM, Frustrated wrote:
> is the only argument really about performance when creating
> structs vs creating classes
Not only creating but also when using. A class variable is a reference
to the actual object, implemented by the compiler as a pointer. So,
there is that extra indirection overhead to access member variables of a
class object.
When the class variable and the object are far apart in memory, they may
be fall outside of CPU caches.
Further, unless they are defined as final or static, class member
functions are virtual. Virtual member funtions are dispatched through
the virtual function table (vtbl) pointer. So, a call like o.foo() must
first hit the class vtbl in memory, read the value of the function
pointer off that table and then jump to the function.
Related to the above, class objects are larger than struct objects
because they have the extra vtbl pointer, as well as another pointer
(monitor) that allows every class object to be used as a synchronization
item in concurrency.
Larger objects are more expensive because less of those can fit in CPU
caches.
> Basically that boils down to stack allocation vs heap allocation speed?
Not to forget, struct objects can be allocated on the stack as well by
std.typecons.scoped.
> Which, while allocation on the heap shouldn't be too much slower than
> stack, the GC makes it worse?
Stack allocation almost does not exist as some location on the stack is
reserved for a given object. There is no allocation or deallocation cost
at runtime other than certain decisions made by the compiler at compile
time.
On the other hand, any dynamic allocation and deallocation scheme must
do some work to find room for the object at runtime.
Ali
More information about the Digitalmars-d-learn
mailing list