Pergunta

I'm tweaking an algorithm that analyzes large amounts of data to make it run a little faster. It makes heavy use of clone functions like the following:

const Object* clone() const {
    if (this != INVALID_OBJECT) {
        return new DerivedObject(*this);
    } else {
        return this;
    }
}

The algorithm uses a pointer to a single invalid object to dramatically reduce memory requirements, and passing it through a copy constructor would defeat the purpose.

My question is whether using short circuit evaluation would increase the performance of the clone functions by reducing execution time:

const Object* clone() const {
    const Object* clonedObject = INVALID_OBJECT;
    (void)((this != INVALID_OBJECT)&&(clonedObject = new DerivedObject(*this));
    return clonedObject;
}

Is there any way to reduce the execution time of the clone functions? The copy constructors generally follow the pattern

DerivedObject(const DerivedObject& derivedObj) : Object(derivedObj.getField1()),
    field2(derivedObj.getField2()) {}
Foi útil?

Solução

Your optimization, complex as it may seem, is actually trivial, in the sense that it likely emits the same code than the previous one.

Think in low level operations, not syntax: one condition, one branch. It is difficult to do less.

UPDATE: I've noticed that I didn't really answer your question: Can it be done faster? Well, yes! You can write a subclass just for the uninitialized value.

class InvalidObject : public Object
{
public:
    const Object* clone() const {
        return this;
    }
};

And make the global INVALID_OBJECT an instance of this class:

Object *INVALID_OBJECT = new InvalidObject();

Now you don't need the condition in any of the clone() overrides:

class DerivedObject : public Object
{
public:
    const Object* clone() const {
        return new DerivedObject(*this);
    }
};

Naturally, depending on the structure of your hierarchy and the definition of your INVALID_OBJECT instance, you may need to write a Invalid* subclass for each DerivedObject type.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top