为什么在java中实现try-catch块时处理速度会变慢?
我一直在解决一个问题 它只是从控制台逐行阅读并找到部件 其中包含一个模式,并用实际数字替换它 资源: 首先,我尝试使用查找文本的模式,并根据需要通过加或减将其替换为实际数字 我的代码为什么在java中实现try-catch块时处理速度会变慢?,java,Java,我一直在解决一个问题 它只是从控制台逐行阅读并找到部件 其中包含一个模式,并用实际数字替换它 资源: 首先,我尝试使用查找文本的模式,并根据需要通过加或减将其替换为实际数字 我的代码 import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.util.regex.Pattern; import java.util.regex.Matcher;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class ABSYS {
public static void main(String[] args) throws IOException {
int t;
String[] numArray = new String[2];
String[] numArray2 = new String[2];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
t = Integer.parseInt(reader.readLine());
while(t > 0) {
String input = reader.readLine();
if(input.isEmpty()) {
continue;
}
numArray = input.split("\\s{1}=\\s{1}");
numArray2 = numArray[0].split("\\s{1}\\+\\s{1}");
Pattern pattern = Pattern.compile("machula");
Matcher matcher = pattern.matcher(numArray[1]);
if(matcher.find()) {
System.out.println(numArray[0] + " = " + (Integer.parseInt(numArray2[0]) + Integer.parseInt(numArray2[1])));
}
else {
matcher = pattern.matcher(numArray2[0]);
if(matcher.find()) {
System.out.println((Integer.parseInt(numArray[1]) - Integer.parseInt(numArray2[1])) + " + " + numArray2[1] + " = " + numArray[1]);
}
else {
System.out.println(numArray2[0] + " + " + (Integer.parseInt(numArray[1]) - Integer.parseInt(numArray2[0])) + " = " + numArray[1]);
}
}
t--;
}
}
}
我在ideone用120个测试用例实现了它之后得到了这个结果
成功时间:0.14内存:320832信号:0
在那之后,为了测试,我完全改变了,取消了模式和匹配器,改为使用try-catch
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class ABSYS {
public static void main(String[] args) throws IOException {
int t;
String[] numArray = new String[2];
String[] numArray2 = new String[2];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
t = Integer.parseInt(reader.readLine());
while(t > 0) {
String input = reader.readLine();
if(input.isEmpty()) {
continue;
}
numArray = input.split("\\s{1}=\\s{1}");
numArray2 = numArray[0].split("\\s{1}\\+\\s{1}");
int a = 0, b = 0, c = 0;
try {
c = Integer.parseInt(numArray[1]);
try {
a = Integer.parseInt(numArray2[0]);
System.out.println(a+" + "+(c - a)+" = "+c);
}
catch(NumberFormatException nfe) {
b = Integer.parseInt(numArray2[1]);
System.out.println((c - b)+" + "+b+" = "+c);
}
}
catch(NumberFormatException nfe) {
System.out.println(numArray[0] + " = " + (Integer.parseInt(numArray2[0]) + Integer.parseInt(numArray2[1])));
}
t--;
}
}
}
我用同样的输入得到这个结果
成功时间:0.15内存:320832信号:0
我不明白,为什么在删除find方法作业之后,在下一个实现中时间会增加
是否是因为try-catch,如果是,原因是什么?我们可以将内部try-catch放在外部catch块之后,而不是嵌套try-catch。我不知道try-catch嵌套不是一个好主意的确切原因。可能非常有用。我不认为try-catch块对此负责。我假设时间是以秒为单位测量的。那么这个差值只有百分之一秒。这不值得担心。它很可能是记录开始和停止时间的一个工件。。。你的结果取决于很多因素,你无法从中得出任何结论。。。