return this (or similar construct) allows method chaining. Lack of it is painful, because you have to write such code (C#):
var list = new List<string>(); list.Add("hello"); list.Add("world");
Elixir solves it nicely for function chaining, instead of relying on callee it relies on caller (forgive me my mistakes, I don't know Elixir):
list |> add("hello") |> add("world");
But now I have just read this sentence at wikipedia:
Returning an object of built-in type from a function usually carries little to no overhead, since the object typically fits in a CPU register.
On one hand callee does not know if the result will be used or not, on the other hand caller cannot stop callee from setting the result value. So I am skeptical about this "little", but "no overhead"?
Thus MY QUESTION for this very particular pattern (i.e
return this with method chaining) -- can it be optimized with no overhead? How?
Question by example -- say I will write a framework and sprinkle every possible method with
return this just to give ability for method chaining. The question arise -- will user who does not use method chaining will pay the price of lowered performance? How compiler could optimize code that this feature will have zero cost.
Update after first 2 comments -- "cheap"!="free", so maybe another perspective for my question, why the difference "little" vs. "no cost". If it can be guaranteed it is at no cost, we write "no cost", period. So I assume it cannot be guaranteed, thus "little".
Clarification I am not asking how to make another Elixir-like syntax in other language. I am asking how it is possible for compiler to optimize callee-caller interaction on
return this + method chaining (or lack of it, when not used).