为什么使用整数作为令牌?

时间:2011-03-02 20:02:31

标签: compiler-construction

现在有没有充分的理由使用数字来识别令牌?我正在关注Crafting a Compiler

作者提供的代码在这里:

public class Token {
    public final static int ID = 0, FLTDCL = 1, INTDCL = 2, PRINT = 3,
            ASSIGN = 4, PLUS = 5, MINUS = 6, EOF = 7, INUM = 8, FNUM = 9;

    public final static String[] token2str = new String[] { "id", "fltdcl",
            "intdcl", "print", "assign", "plus", "minus", "$", "inum", "fnum" };

    public final int type;
    public final String val;

    public Token(int type) {
        this(type, "");
    }

    public Token(int type, String val) {
        this.type = type;
        this.val = val;
    }

    public String toString() {
        return "Token type\t" + token2str[type] + "\tval\t" + val;
    }
}

不是使用丑陋的数组,修改构造函数以接受type变量而不是整数的字符串是不是更明智?然后我们就可以摆脱

    public final static int ID = 0, FLTDCL = 1, INTDCL = 2, PRINT = 3,
            ASSIGN = 4, PLUS = 5, MINUS = 6, EOF = 7, INUM = 8, FNUM = 9;

或者是否需要以后使用字符串会更糟?

1 个答案:

答案 0 :(得分:2)

有几个好处:

  • 它更快,因为比较两个整数(在你的平均编译语言中)只需要几个指令,而比较字符串需要O( n )时间,其中<​​em> n 是较大令牌的长度。 Compilers need this extra bit of speed
  • 在C,C ++和Java中,您可以switch int而不是字符串。
  • 对令牌名称进行错误输入将是编译时错误,而不是难以调试的运行时错误。