java - 考虑 "if"语句和异常的长期性能成本

标签 java performance exception

我一直认为使用“if”比捕获异常要好得多(就性能而言)。例如,这样做:

User u = Users.getUser("Michael Jordan");
if(u!=null)
   System.out.println(u.getAge());

对比

User u = Users.getUser("Michael Jordan");
try{
   System.out.println(u.getAge());
}catch(Exception e){
   //Do something with the exception
}

如果我们对此进行基准测试,很明显第一个片段比第二个片段快。这就是我一直认为的。 但是,昨天,一个人告诉我这样的话:

Have you ever considered what happens in thousands of executions of your programs? Every time your execution goes through your "if" you've a little (real little, but still something) performance cost. With exceptions it doesn't happens. Becouse it could never arise.

明确一点:数千次执行“if”与一次异常捕获。

我觉得有道理,但是没有证据。

你能帮帮我吗?

谢谢!!

最佳答案

没有。一旦 JIT 启动,就不会告诉他继续阅读 trace caches .

A dynamic trace ("trace path") contains only instructions whose results are actually used, and eliminates instructions following taken branches (since they are not executed); a dynamic trace can be a concatenation of multiple basic blocks. This allows the instruction fetch unit of a processor to fetch several basic blocks, without having to worry about branches in the execution flow.

基本上,如果每次通过循环体都采用相同的分支,那么该循环体最终将作为跟踪缓存中的单个跟踪。处理器不会产生获取额外分支指令的成本(除非将基本 block 推送到跟踪缓存中可以存储的限制之外,不太可能)并且在开始之前不必等待测试结果执行以下指令。

关于java - 考虑 "if"语句和异常的长期性能成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5411620/

相关文章:

java - 使用 ch.ethz.ssh2.Connection 使用 JAVA 进行 SSH 连接

sql - Oracle 不能推断这些查询是相同的——生成了非常不同的执行计划

javascript - 通用选择器的性能,结果矛盾?

java - Swing 文本组件无法从剪贴板粘贴大文本数据 : java. io.IOException: Owner failed to convert data

c# - 将异常保存到数据库的安全最大 varchar 大小是多少?

.net - 为什么 UnhandledExceptionEventArgs.ExceptionObject 是一个对象而不是 Exception?

java - 哪些方法可用于从 Java 文件中返回有效和无效的 XML 数据?

java - gwt bootstrap 中带有切换按钮的水平控制组

java正则表达式用{var}次{var}px替换{var}px

c++ - 重载数组下标 [] 运算符慢