Does private class member return slower than using structure and accessing this variable directly?

Suppose you have a class that has private members, which the program has a lot of access to (for example, in a loop that should be fast). Imagine I defined something like this:

class Foo
{
public: 

    Foo(unsigned set)
        : vari(set)
    {}

    const unsigned& read_vari() const { return vari; }

private:
    unsigned vari;
};

The reason I would like to do this is because after creating the class "vari" should no longer be changed. Thus, to minimize the appearance of errors, "at the time, this seemed like a good idea."

However, if I now need to call this function millions of times, I was wondering if there is overhead and slowdown instead of just using it:

struct Foo
{
    unsigned vari;
};

, , , - , ? , "" . (, , -O2 GCC)?

+4
4

. , , operator[] gdb, optimized out? . , .

struct foo{
   int x;
   int& get_x(){
     return x;
   }   
};

int direct(foo& f){ 
   return  f.x;
}

int fnc(foo& f){ 
   return  f.get_x();
}

g++ test.cpp -o test.s -S -O2. -S : " , ( g++)". , :

_Z6directR3foo:
.LFB1026:
  .cfi_startproc
  movl  (%rdi), %eax
  ret 

_Z3fncR3foo:
.LFB1027:
  .cfi_startproc
  movl  (%rdi), %eax
  ret 

, , . , .

: , ? , :

_Z6directR3foo:
.LFB1022:
  .cfi_startproc
  pushq %rbp
  .cfi_def_cfa_offset 16
  .cfi_offset 6, -16
  movq  %rsp, %rbp
  .cfi_def_cfa_register 6
  movq  %rdi, -8(%rbp)
  movq  -8(%rbp), %rax
  movl  (%rax), %eax
  popq  %rbp
  .cfi_def_cfa 7, 8
  ret

_Z3fncR3foo:
.LFB1023:
  .cfi_startproc
  pushq %rbp
  .cfi_def_cfa_offset 16
  .cfi_offset 6, -16 
  movq  %rsp, %rbp
  .cfi_def_cfa_register 6
  subq  $16, %rsp
  movq  %rdi, -8(%rbp)
  movq  -8(%rbp), %rax
  movq  %rax, %rdi
  call  _ZN3foo5get_xEv    #<<<call to foo.get_x()
  movl  (%rax), %eax
  leave
  .cfi_def_cfa 7, 8
  ret

, sturct , Accessor, ?

+9

. ++ - , , ++ 11 list::size() const . ( vector(), , , size() , begin() end(), , , size() ).

, const unsigned, CPU , , ( out- , , , ). ( , , vector::operator[](size_t) const const T&, T, T , .)

+5

, , , - .

Having said that, it is likely that the binary files will be identical, an instruction for learning.

0
source

As others have said, optimizers today rely on throwing away abstraction (especially in C ++, which is more or less built to take advantage of this), and they are very, very good.

But for this you may not need a getter.

struct Foo {
    Foo(unsigned set) : vari(set) {}
    unsigned const vari;
};

const does not prohibit initialization.

0
source

Source: https://habr.com/ru/post/1536900/


All Articles