Home > database >  C Is there a performance difference when assigning a new value to a variable vs assigning them via
C Is there a performance difference when assigning a new value to a variable vs assigning them via

Time:11-23

I've been mostly using private variables when writing a class and using methods to set the variable's value.

Especially when it comes array, indexing them would be just using the operator[]. But what if I were to put them inside a method like getIndex(int x), and calling that method. Would that have any impact to the performance like slowing it down a little bit?

CodePudding user response:

This question can be a start of a much bigger discussion to explore deep philosophical issues.

First, this sounds very much like premature optimization. I would advise you to first worry about the design of your class and its interface, and then worry about the performance. Most often the compiler is smarter than you when it comes to low-level optimization like this.

In your example you are talking about getting values, not setting values, and that is important. Your data members generally should be private, and then you need to think about what interface your class should have. Depending on how your class is used, you may need a getItem(int idx), which returns an item at the given index, or you may need a getItems(), which returns the whole array of items.

For setting the values, you generally want to be more careful, because you want to limit the ways the clients of your class can mess with your object. You definitely do not want to have a setter for every data member, because that is almost as bad as making the data members public.

Some data members may need to be set together, because you want to validate some condition involving them. Some data members should not be modifiable by the users of your class at all.

CodePudding user response:

That really depends on whether the compiler can inline the calls to these getters/setters.

It can inline them if either:

  • Each translation unit has access to their definitions - in practice if they are in the header file of the class. Either inlined into the class definition or inline-defined after it.
  • You enable link-time optimizations.

Any decent compiler with optimizations enabled will inline simple getters/setters if possible and in that case the assembly will be exactly the same.

But should you care? No. Write clean code first.

Unless you can prove with a benchmark there are performance issues stemming from this. And in that case, enable LTO or put the definitions in the headers.

On the other hand, having the members private and the access hidden behind methods is very good abstraction. If you ever decide to e.g. implement bounds checking, good luck refactoring all those object.array[idx] expressions across the code base.

  • Related