If my program does this: myarr[5] is that really faster than mystruct.value_5 |
No.
The "classes are slow" BS stems from the fact that member function and variable access adds another level of indirection.
Consider the below:
1 2 3 4 5 6 7 8 9
|
class A
{
int avar;
void function()
{
avar = 5; // doesn't look like it, but this involves a pointer dereference
}
};
|
Here,
avar = 5;
is
actually this->avar = 5;
. The added indirection of
this
does in fact involve some overhead.
However this doesn't make classes any slower than structs. The same thing could be done in C:
1 2 3 4 5 6 7 8 9
|
typedef struct
{
int avar;
} A;
void function(A* a)
{
a->avar = 5;
}
|
This code, and the above C++ code are pretty much identical.
Now where it gets even more complicated is with virtual function calls. Calling a virtual function 'foo':
virtual void foo();
involves a bit more overhead:
- possibly some pointer math to find the vtable (if you have multiple inheritance or somesuch)
- dereferencing the vtable to find the right 'foo' function pointer
- dereferencing the function pointer to actually call the function
So yeah this is a little slower, but it's nothing to write home about.
And again.. the same thing could be accomplished in C... and doing it in C would not be any faster because you'd have to do all of the same work.
So C++ isn't slower than C. What's really the case is that slower language constructs are slower than faster language constructs, and C++ overs more slower language constructs to the programmer.
And I use the term "slower" here very loosely. The above overhead is
miniscule and 9999 times out of 10000 will not hinder your program's performance in any way shape or form, unless you're doing it a few hundred thousand times per second.