user1870400
user1870400

Reputation: 6364

How to write the logical operations of grammar rule in the most optimized way in antlr4?

How to write the logical operations of grammar rule in the most optimized way in antlr4?

For example,

Approach #1

logicalExpression: expression ('EQUALS' | 'NOT EQUALS' | 'GREATER_THAN' | 'LESS_THAN') value;

vs

Approach #2

logicalExpression
    : expression 'EQUALS' value
    | expression 'NOT EQUALS' value
    | expression 'GREATER_THAN' value
    | expression 'LESS_THAN' value

Which is approach is more efficient/performant? and Why? I have a feeling expression will be matched multiple times in approach#2 rather than just once.

Upvotes: 0

Views: 70

Answers (1)

Mike Lischke
Mike Lischke

Reputation: 53522

The first approach is more efficient. Just look at the underlying ATN:

enter image description here

versus

enter image description here

When the parser walks the ATN to predict the match it has to check one path after the other. In the second approach it has to evaluate the left hand expression node for every possible operator. The first variant is much more efficient, since it evaluates that only once and quickly decides based on a single operator check, instead.

Upvotes: 1

Related Questions