1

If I have a glm::vec3 for example and I want to assign a new value to it, which of the following methods is faster?

vec = glm::vec3(1, 2, 3);

or

vec.x = 1;
vec.y = 2;
vec.z = 3;

If I understand correctly, the first method does the following:

  1. Calls the glm::vec3 constructor to create a new temporary vector on the stack
  2. Calls the copy assigment operator of glm::vec3 to copy the new vector

Whereas the second method is just assignments and avoids creating a dummy temporary vector, so why I would ever want to do a ton of *** instead of just assigning my values?

Jojolatino
  • 696
  • 5
  • 11
  • 2
    Profile, profile, profile. That being said, the first is faster. – Eljay Apr 15 '20 at 21:49
  • 4
    All the compiler has to generate is code that behaves **as if** your two steps have happened. No compiler would actually generate code that stupid. Leave micro-optimizations to the compiler and concentrate on clarity of code instead. – john Apr 15 '20 at 21:57
  • @Eljay Is it? Did you _profile_ to determine that? I'd bet the assembly is identical. – Asteroids With Wings Apr 15 '20 at 22:12
  • 1
    @AsteroidsWithWings is right [exactly same code for both versions](https://godbolt.org/z/FMWici). Difference appears when `-O1` is used. – Marek R Apr 15 '20 at 22:18
  • I suppose it would be better to have phrased it "the first will be as fast or faster than the latter; the latter will be as fast or slower than the former." – Eljay Apr 16 '20 at 01:39

2 Answers2

3

Don't overthink it.

You're not actually programming a computer; you're describing a program. It is your compiler's job to create the program that will be executed by a computer, using your description. This is the practical reality powered by the C++ standard's "as-if" rule: the compiler is under no obligation to follow your "steps" one by one, as long as the observable results of the real (compiled) program match your description (source code).

Your compiler is very, very clever. It is more than capable of ensuring that it does not perform excess, additional, unnecessary steps for cases like this, whichever way you write it. For me*, the resulting assembly for both approaches is identical, unless you lower the optimisation level (which is really increasing the "make the program look more like the steps in my description" level, a debugging feature).

Just write clear, self-documenting, straightforward code that reflects your intention. Only when you have some situation where the compiler has perhaps not done the best job it could, do you intervene with questions like this.

* Okay, it was Marek

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
0

Yes, when you're calling glm::vec3, it is going to construct that object, but there is really no much of a performance difference between the two, if this is what you are complaining about. So, you can use either of them, but the first one is just better to look at.

fufupati
  • 77
  • 5