考虑到你有这样的代码:
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需要多长时间(以纳秒为单位)(假设消息具有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)