natalie icon indicating copy to clipboard operation
natalie copied to clipboard

Object#is_a? is not very efficient

Open herwinw opened this issue 11 months ago • 0 comments

The current code

bool Object::is_a(Env *env, Value val) const {
   if (/* direct match (instance_of?), not relevant here */) {
    } else {
        ClassObject *klass = singleton_class();
        if (!klass)
            klass = m_klass;
        ArrayObject *ancestors = klass->ancestors(env);
        for (Value m : *ancestors) {
            if (module == m->as_module()) {
                return true;
            }
        }
        return false;
    }
}

In other words: unless we have a direct match, we first build a list of all the ancestors, then loop through the results to see if the wanted value is in it.

This could be done more efficient by removing the temporary array and directly looping with a method. The current code is pretty much like enumerable.to_a.include?(val), which could be written as enumerable.include?(val).

herwinw avatar Mar 05 '24 18:03 herwinw