我读过一些有关在循环内声明对象的其他问题,例如:
Is it Better practice to Declare individual objects or loop Anonymous objects into ArrayList?
Java : declaring objects in a loop
但两者都没有真正解决我的问题。
我重复扫描用户输入并创建一个类来每次迭代解析该字符串:
public static void main(String[] args) {
while (true) {
System.out.print("Enter a string of brackets to test: ");
String exp = new Scanner(System.in).nextLine().trim();
if (exp.equals("q")) break; // q is the 'quit' flag
System.out.println(new BracketMatcher(exp.length()).parse(exp));
}
}
与此 block 有什么区别 - 性能,而不是范围?:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
BracketMatcher matcher;
while (true) {
System.out.print("Enter a string of brackets to test: ");
String exp = input.nextLine().trim();
if (exp.equals("q")) break; // q is the 'quit' flag
matcher = new BracketMatcher(exp.length());
System.out.println(matcher.parse(exp));
}
由于我只使用该方法,因此将 parse() 设为 BracketMatcher 中的静态方法会更好吗?
谢谢。
最佳答案
代码中的性能差异来自于在每次迭代中创建一个新的扫描仪(这很愚蠢,甚至可能无法可靠地工作,具体取决于扫描仪的缓冲方式)。
声明变量的位置本身不会影响性能。
就我个人而言,我会创建一次 Scanner(因为它应该读取所有行,而不仅仅是一行),但会在循环内部创建 BracketMatcher(因为它与当前行相关)。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("Enter a string of brackets to test: ");
String exp = input.nextLine().trim();
if (exp.equals("q")) break; // q is the 'quit' flag
System.out.println(new BracketMatcher(exp.length()).parse(exp));
}
}
Would I be better off making parse() a static method in BracketMatcher since I only use that method?
我不知道你的 BracketMatcher 是做什么的,也不知道无论输入如何都可以准备任何东西。例如,正则表达式匹配器可以为固定表达式编译一次,然后重新用于许多字符串进行匹配。在这种情况下,您可以将 BracketMatcher 保留为有状态对象,并在循环外创建一次。
关于Java循环对象声明最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23820253/