哪一个更快:
这个
try {
n.foo();
}
catch(NullPointerException ex) {
}
Run Code Online (Sandbox Code Playgroud)
要么
if (n != null) n.foo();
Run Code Online (Sandbox Code Playgroud) 考虑到你有这样的代码:
doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing the same kind of exceptions.
Run Code Online (Sandbox Code Playgroud)
现在我知道,实际上在构造异常时会出现性能损失,特别是展开堆栈.我还阅读了几篇文章,指出在输入try/catch块时会有轻微的性能损失,但这些文章似乎都没有结论.
我的问题是,是否建议将try catch中的行保持最小?,即只在try子句中包含可以实际抛出正在捕获的异常的行.try子句中的代码运行速度较慢或导致性能下降吗?
但考虑到这一点,更重要的是最佳实践/更易读的解决方案:
try {
doSomething() // this method may throw a checked a exception
//do some assignements calculations
doAnotherThing() //this method may also throw the same type of checked exception
//more calls to methods and calculations, all throwing …Run Code Online (Sandbox Code Playgroud) try/catch在Java中使用块而不是使用多个If语句来检查用户输入是否更好,更便宜或更具可读性?
解析Date字符串时的示例,使用try/catch块直接解析而不是编写查找非法字符的多个语句不是更好.
在另一个例子中,假设我想要读取文件或流,而不是使用Scanner,我只是强制该方法并等待发生异常.
这是一种健康的编程方法吗?它在虚拟机上更便宜吗?
更新
这里是我在使用DateFormat异常时的意思的一个例子,有时它可能是一个真正的问题来捕获错误,并且这样做,你能保证你的复杂(通常是不可读)代码容易出错吗?
捕获异常而不是进行检查时,try-catch需要多长时间(以纳秒为单位)(假设消息具有HashMap类型的查找性能)?
try {
timestamp = message.getLongField( MessageField.TIMESTAMP );
} catch (MissingDataException e) {
//Not all messages contain this field
}
Run Code Online (Sandbox Code Playgroud)
VS
if (message.contains(MessageField.TIMESTAMP))
timestamp = message.getLongField( MessageField.TIMESTAMP );
Run Code Online (Sandbox Code Playgroud) 这是一个简单的问题:
您如何看待每次使用try catch的代码?
void myfunction() {
try {
instruction1();
}
catch (ExceptionType1 e) {
// some code
}
try {
instruction2();
}
catch (ExceptionType2 e) {
// some code
}
try {
instruction3();
}
catch (ExceptionType3 e) {
// some code
}
try {
instruction4();
}
catch (ExceptionType4 e) {
// some code
}
// etc
}
Run Code Online (Sandbox Code Playgroud)
我知道这太可怕了,但我想知道这是否会降低性能.