Most efficient way to mutate data member

157 views Asked by At

I've been wondering about this question for a long time. What is the most idiomatic and / or efficient way to assign a new value to a data member (mutation)? I can think of 3 options:

  • Mutate directly from within method
  • Use a reference to mutate object
  • Assign the return value of the method to the data member (RVO)

Here's a demo. Please consider while reading the assembly that the compiler optimizes away probably most of the differences in this contrived example, but I just wanted to showcase the options in the most simple way. Please answer for the case where this methods are more involved.

Demo

#include <string>
#include <cstdio>

struct some_struct
{

    auto assign_direct() {
        str_ = "Hello World!";
    }

    auto assign_through_ref(std::string& ref) {
        ref = "Hello World!";
    }

    auto assign_through_RVO() {
        const std::string ret = "Hello World!";
        return ret;
    }

    void internal_func() {

        assign_direct();

        assign_through_ref(str_);

        str_ = assign_through_RVO();
    }

    std::string str_;
};

int main()
{
    some_struct s;
    s.internal_func();
}

My thought is that both, direct assignement and copy assignement must be equally efficient as they dereference the this-pointer and then dereference the effective address of the data member. So two dereferences are involved while the assign_thorugh_ref method only ever uses one dereferencing (except that this must be dereferenced to even call the method, but maybe this can be optimized away by an intelligent compiler).

Also what I want to know is what is most idiomatic / clear and least error prone? Maybe someone with some more years than me can give me some insights here!

0

There are 0 answers