-1

For quite a long time I've been using javascript where this keyword is mandatory. Now, I'm programming in c++ but habit of using this keyword remained. But the real question is - Does using this keyword have any negative impact on performance (as in unnecessary memory access)? I mean - is code omitting this more optimization friendly for compiler or it completely doesn't matter? Because well strictly theoretically, referring to this is kind of referring to pointer, like opcode $reg0, [$reg1] in assembler, which could add one more memory reference in code but i guess it should be handled by compiler in more clever way than just typical pointer, am i right?

Personally I prefer using this because I feel a bit lost in code which doesn't use it as i don't know if some variables are members or they're local or global or what, but if it'd cause performance issues I could probably force myself to avoid it.

Lapsio
  • 6,384
  • 4
  • 20
  • 26
  • 2
    There's no difference. Write whatever you prefer. – Kerrek SB Dec 12 '15 at 17:46
  • 2
    You can use [gcc.godbolt.org](http://goo.gl/t7ncvy) to add and remove `this->` and see if the generated assembly changes. (It does not, even without optimizations.) – Emil Laine Dec 12 '15 at 17:51
  • @zenith: I think questions about optimization are completely confused. Adding `this->` is a pure syntax-level detail. The *meaning* of expression is absolutely the same, and of course you need to interpret a member name relative to some object instance. – Kerrek SB Dec 12 '15 at 17:54

2 Answers2

5

No, an optimizing compiler (for C++11 or better) would very probably generate the same binary code for this->field and for field, and likewise for this->memberfun(2,3) and memberfun(2,3).

(probably, even without optimization, the same -inefficient- code would be produced; but I am not sure of that)

Sometimes (notably when coding templates) this is required because omitting it has different meaning (I forgot for which weird cases).

Of course, the compilation time might be slightly different. But you should not care.

Some coding conventions require, or (more often) on the contrary forbid, using this for readability reasons. Choose whatever convention you like, but be consistent.

See also this answer explaining how practically this is handled on Linux x86-64 ABI.

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
4

But the real question is - Does using this keyword have any negative impact on performance (as in unnecessary memory access)?

no.

which could add one more memory reference in code but i guess it should be handled by compiler in more clever way than just typical pointer, am i right?

yes

:-)

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142