3
votes

I am trying to parse java files using ANTLR4 and walk the parse tree searching for specific function calls.

While I am able to achieve this using both Visitor and Listener approach, but stress tests reveals that Listeners are faster compared to Visitors, which goes contrary to popular belief.

Theoretically, Visitors are supposed to be faster as they would only inspect specific node, where as listeners inspect all. Anyone know why this would be the case?

1
"contrary to popular belief" any references on that? "as they would only inspect specific node" how is ANTLR supposed to know which node(s) to skip and which to visit? ANTLR's listeners and visitors traverse all nodes. I'd guess the runtimes between the two are negligible.Bart Kiers
Antlr4 Listeners and Visitors - which to implement?. According to this resource, If I visit only the nodes I need I would be saving time as I am not calling visit method for other nodes(because they will never be visited) but Listener will traverse all the nodes, shouldn't this be more time consuming?ramos
But using a default visitor wil walk the entire tree. So if you extend a default visitor, and override a few visit...(...) methods, all nodes will be visited.Bart Kiers
Yeah, I get it now. Thanksramos

1 Answers

4
votes

In ANTLR, listeners should be faster than visitors, though the performance difference will be less than easily measurable, if at all.

Listeners use the walker algorithm in ParseTreeWalker. Visitors use the algorithm in AbstractParseTreeVisitor. Both 'consider' all nodes.

Beyond the slight implementation differences, the one quantitative difference is that visitor calls involve the overhead of generic return type processing. Still, should be a negligible impact on performance in any modern JVM.