digitalmars.D.learn - this r-value optimizations
- =?UTF-8?B?Tm9yZGzDtnc=?= (39/39) Aug 01 2017 Given the `struct S` with lots of data fields, I've written the
- Moritz Maxeiner (14/31) Aug 01 2017 You're going to have to be specific about optimized out by whom.
Given the `struct S` with lots of data fields, I've written the following functional way of initializing only a subset of the members in an instance of `S`: struct S { int i; float f; ... this(int i) { this.i = i; } S withF(float f) { // will this be optimized out if `this` is an r-value? S copy = this; copy.f = f; return copy; } } Now the question becomes: will the S-copying inside `withF` be optimized out in the case when `this` is an r-value such as in the call auto y = S(32).withF(42.0); ? If not, one solution of doing this manually is to write `withF` as a free function S withF()(auto ref S this_, float f) { static if (__traits(isRef, this_)) { // this_ is an l-value (and was passed by ref) // so a copy has to be made before modifying it } else { // this_ is an r-value (and was passed by move) // so it can be modified in-place } } Is this the preferred way of solving this until we (ever) get named parameters in D?
Aug 01 2017
On Tuesday, 1 August 2017 at 22:47:24 UTC, Nordlöw wrote:Given the `struct S` with lots of data fields, I've written the following functional way of initializing only a subset of the members in an instance of `S`: struct S { [...] } Now the question becomes: will the S-copying inside `withF` be optimized out in the case when `this` is an r-value such as in the call auto y = S(32).withF(42.0); ?You're going to have to be specific about optimized out by whom. By the frontend? Doesn't seem that way to me by looking at the `-O0` assembly generated by ldc [1].If not, one solution of doing this manually is to write `withF` as a free function [...] Is this the preferred way of solving this until we (ever) get named parameters in D?Preferred by whom? The people who want named parameters in D seem to be a minority in the community from my personal observation, so you would most likely get personal preferred way as an answer (instead of "the" unanimous preferred way). In any case, this looks like a case of evil early optimization to me, because it's statistically unlikely that this is going to be the bottleneck of your program (though profiling would be in order to confirm / disprove that assumption for your specific use case). [1] https://godbolt.org/g/Htdtht
Aug 01 2017