Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will GCC optimize away an inline accessor?

Let's say I have this class

class Point 
{
  inline float x() const { return v[0]; }
  inline float y() const { return v[1]; }
  inline float z() const { return v[2]; }

  float v[3];
};

And I do:

Point myPoint;
myPoint[0] = 5;

// unrelated code goes here

float myVal = myPoint.x() + 5;

Will GCC on -O2 or -O3 optimize away any calls to x() with just getting v[0]? IE:

float myVal = myPoint.v[0] + 5;

Or is there a reason why this is impossible?

Update: Should mention I do realize inline is more of a suggestion to the compiler than anything else, but was wondering anyways.

As an additional question, will templating this class have any effect on the optimizations that can be done?

like image 477
Tyler Shellberg Avatar asked Jun 18 '26 15:06

Tyler Shellberg


2 Answers

Will GCC optimize away an inline accessor?

All optimizing compilers will do so. It is a trivial optimization compared to other ones.

Or is there a reason why this is impossible?

There is no reason that makes it impossible, yet there is no guarantee either.

As an additional question, will templating this class have any effect on the optimizations that can be done?

No. But, of course, a compiler may have different inlining thresholds for templates.

like image 125
Acorn Avatar answered Jun 21 '26 04:06

Acorn


It may or may not be inlined. No guarantees there. But if you want it to be always inlined, use the [[gnu::always_inline]] attribute. See the docs here. Use this attribute only if you know what you're doing. In most cases it's best to let the compiler decide what optimizations are suitable.

like image 32
Ayxan Haqverdili Avatar answered Jun 21 '26 03:06

Ayxan Haqverdili



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!