C++ performance of accessing member variables versus local variables

后端 未结 11 2024
别那么骄傲
别那么骄傲 2020-12-04 22:07

Is it more efficient for a class to access member variables or local variables? For example, suppose you have a (callback) method whose sole responsibility is to receive dat

11条回答
  •  抹茶落季
    2020-12-04 22:27

    A few points that have not been mentioned explicitly by others:

    • You are potentially invoking assignment operators in your code. e.g varC = msg.getString();

    • You have some wasted cycles every time the function frame is setup. You are creating variables, default constructor called, then invoke the assignment operator to get the RHS value into the locals.

    • Declare the locals to be const-refs and, of course, initialize them.

    • Member variables might be on the heap(if your object was allocated there) and hence suffer from non-locality.

    • Even a few cycles saved is good - why waste computation time at all, if you could avoid it.

提交回复
热议问题