Getting rid of unnecessary temporary objects in calculations? (Suggestion)
Don Clugston
dac at nospam.com.au
Tue Oct 24 23:33:04 PDT 2006
Kristian wrote:
>
> Lets consider the following:
>
> class Foo {
> Foo clone() {
> Foo ret = new Foo;
>
> ret.val = val;
>
> return(ret);
> }
>
> Foo opAdd(Foo Obj) {
> return(clone() += Obj);
> }
>
> Foo opAddAssign(Foo Obj) {
> val += Obj.val;
> return(this);
> }
>
> int val;
> }
>
> Usually 'opXxx' and 'opXxxAssign' are closely related: 'a = a + b' <->
> 'a += b'. It would be very strange if that were not true.
>
> So, if a class has 'opXxx'/'opXxxAssign' it normally it has also
> 'opXxxAssign'/'opXxx', and a clone function.
>
> The compiler could then automatically generate 'opXxx' functions if a
> class has a standard clone operator, e.g. 'opClone'. Of course, you can
> easily mixin the 'opXxx' functions by yourself. But lets consider the
> following next:
>
> Foo a, b, c, d;
>
> a = b + c + d;
>
> A temporary object is created here two times. One should be sufficient.
>
> For example, you have a HugeMatrix class you use calculations, it gets
> cloned more than once, which is unnecessary. That can prevent operators
> to be used at all (too much time would be spend on cloning).
>
> What if compiler assumes that the 'opXxx' operators always return
> temporary objects? Then "a = b + c + d;" would be read as:
>
> a = b.opAdd(c).opAddAssign(d);
>
> That's efficient.
>
>
> Now, what if we get rid of the 'opXxx' operators altogether?
>
> If a class has 'opClone', then the class is treated as a value type:
> statements are compiled with the 'opClone' and 'opXxxAssignment'
> operators only. For example, "a = b + c + d;" will be read as:
>
> a = b.opClone().opAddAssign(c).opAddAssign(d);
>
> Then you could always use operators freely and there would be no
> redundant operator functions (e.g. 'opAdd' *and* 'opAddAssign'). Of
> course, that would also enforce 'a = a + b' <-> 'a += b' to be true
> always, but I think so it should be.
>
> And if there will be a copy/clone operator, lets say '<-', then
>
> a <- b;
> a <- b + c;
>
> would be, of course, read as:
>
> a <- b; //== a = b.opClone();
> a = b + c; //== a = b.opClone().opAddAssign(c);
Take a look at:
http://d.puremagic.com/bugzilla/show_bug.cgi?id=124
which also deals with cases like
a = b - a;
More information about the Digitalmars-d
mailing list