gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:02:30 30 4
gpt4 key购买 nike

我一直认为使用“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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com