Memory and Processing Time – Class Member Function vs Global Function in C++

cclasscompilationmemory usage

I'm writing a neuron network simulation program and every operation or additional byte per neuron scales insanely. I prefer C++ as a language over the others, but now I'm wondering if the class structure takes additional space or resources after compilation in comparison to C for example. If I have a :

class Neuron{
float some,variables,foo,bar;
//And some functions to compute the changes
void foo();
void bar();
}

will it be leaner to have a :

struct Neuron{
float some,variables,foo,bar;
}
void foo(Neuron*);
void bar(Neuron*);

or is it the same after compilation?

Best Answer

If you don't use virtual functions, then there should be no (negative) performance or space impact on using C++ classes when comparing to C structs. The two snippets you gave as example should compile to (nearly) the same assembly code.1

If you add virtual functions to your classes, then there will be a slight memory overhead per object (about the size of a pointer) and a time overhead per call to a virtual function, because the call has to go through a dispatch table. It will also be an indirect jump, which might be slightly more costly on some processor architectures (in the order of a few clock cycles).

Note 1: The compiler may use a different method for passing the implicit this parameter than what is used for the other parameters, but that difference is in the order of choosing register A instead of B or passing in a register instead of on the stack.

Related Topic