If you are referring to method cascading, you'd have this:
class Object
{
public:
Object& Method1()
{
// do something
return *this;
}
Object& Method2()
{
// do something
return *this;
}
Object& Method3()
{
// do something
return *this;
}
};
So calling the functions like this
obj.Method1().Method2().Method3();
Is functionally equivalent to
obj.Method1();
obj.Method2();
obj.Method3();
In short, there is no performance hit. It is nothing more than a convenience idiom. The one problem you face is that, since you are forced to return a reference to this
, you cannot return something meaningful (e.g. the result of these functions).
If you are referring to method chaining:
Each method must return some object that has the corresponding method that follows in the chain:
class Object
{
public:
std::vector<int>& Method1()
{
// do something
return _vec;
}
private:
std::vector<int> _vec;
};
So calling
obj.Method1.size();
Is identical to calling
std::vector<int>& vec = obj.Method1();
vec.size();
So again, there is no performance hit.
However, if you were to change Method1
to return by copy instead of by reference, it is possible to have a performance hit (e.g. if the vector is actually copied).
Though, I think you worded your question poorly. Your second example has 2 less function calls per iteration, so yes, it will be more efficient than calling 3 functions per iteration. But, I don't think that is really what you were asking about.