问题
I've built a basic parser using the C++ runtime demo and it works fine. However I typically parse a lot of input strings, can the code be modified to reuse existing objects for repeated calls? If so, does anyone have an example of this?
回答1:
Yes, reusing the objects is possible. A typcial sequence for a parse call looks like this then:
input.load(newText);
errors.clear();
lexer.reset();
lexer.setInputStream(&input); // Not just reset(), which only rewinds the current position.
tokens.setTokenSource(&lexer);
parser.reset();
...
This could be part of a parser service class. All the objects (parser, lexer, token stream, input stream) are created in the c-tor of this class and the code above is then called for each parse operation.
However, you don't win much by reusing these objects. Creation is cheap and the heavy data is held statically, so it doesn't need to be recreated on each parser creation.
来源:https://stackoverflow.com/questions/48700598/reuse-antlr-objects-for-a-new-input-string-c-runtime