Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a getter have zero cost?

I have a simple class:

class A {
    public:
    int get() const;

    private:
    void do_something();
    int value;
}

int A::get() const {
    return value;
}

The getter function is simple and straightforward. Getters are to use them, so in do_something I should use get() in order to access value. My question is: will compiler optimize-out the getter, so it will be equivalent to accessing the data directly? Or I still will gain performance if I access it directly (what would imply worse design)?

A::do_something()
{
    x = get();
    // or...
    x = value;
}
like image 474
Jakub M. Avatar asked Oct 24 '11 09:10

Jakub M.


2 Answers

When the method is not virtual, compilers can optimize it. Good compilers (with link-time optimization) can optimize even if the method is not inline and defined in separate .cpp file. Not so good ones can only do that if it's declared inside the class definition, or in the header file with inline keyword. For virtual methods, it depends, but most likely no.

like image 106
hamstergene Avatar answered Sep 21 '22 07:09

hamstergene


The compiler will almost certainly inline such a trivial getter, if it's got access to the definition.

like image 31
Puppy Avatar answered Sep 23 '22 07:09

Puppy