(blog-of ‘Alex’)

A personal blog about software development and other things. All opinions expressed here are my own, unless explicitly stated.

What is faster: multiple instanceofs or visitor?

I was always curious on whether visitor pattern is more effective than using multiple instanceof when it comes to detect whether the given base implements certain interface or not.

To do this comparison, I had 7 interface classes and visitor for all of these, and 7 concrete implementations, then I tested instanceof and visitor pattern on a large collection of randomly picked instances of these classes, the timing for 100000 objects was as follows on my machine (best value is taken for several interations of both benchmarks, the less is of course the better):

instanceof: 5.055 sec
visitor: 3.511 sec

The testing code snippets are as follows:

// for instanceof:
    public static int measureInstanceOf(Node[] nodes) {
        int litCount = 0;

        for (int i = 0; i < N; ++i) {
            if (nodes[i] instanceof Literal) {
                ++litCount;
            }
        }

        return litCount;
    }

// for visitor:
    public static final class LiteralCheckerVisitor implements NodeVisitor {
        boolean isLiteral = false;

        public void visitMarker(Marker marker) {}
        // other methods are similar to the given above and skipped

        public void visitLiteral(Literal literal) { isLiteral = true; }
    }

    public static int measureVisitor(Node[] nodes) {
        int litCount = 0;
        final LiteralCheckerVisitor visitor = new LiteralCheckerVisitor();

        for (int i = 0; i < N; ++i) {
            // equivalent of instanceof Literal
            visitor.isLiteral = false;
            nodes[i].accept(visitor);
            if (visitor.isLiteral) {
                ++litCount;
            }
        }

        return litCount;
    }

And here is my java vm version:

java version "1.6.0_24"
Java(TM) SE Runtime Environment (build 1.6.0_24-b07-334-10M3326)
Java HotSpot(TM) 64-Bit Server VM (build 19.1-b02-334, mixed mode)

Conclusion: when it comes to implementing handlers for hierarchy of classes, instanceof is not only worse from the pure maintainability’s standpoint, but even performance-wise.