铸造时 Java 嵌套 Foreach 慢 [英] Java Nested Foreach SLOW When Casting

查看:61
本文介绍了铸造时 Java 嵌套 Foreach 慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Java 编写交换系统,但我似乎遇到了严重的性能问题.

I am writing an exchange system in Java, but I seem to have run into a crippling performance issue.

以下代码是执行变得非常慢的地方:

The following code is where execution becomes VERY slow:

    outer:
    for(ArrayList<Offer> listSell : sellOffers.values()) {
        for(Offer sellOffer : listSell) {
            ArrayList<Offer> listBuy = buyOffers.get(getStorageHash(sellOffer));
            if(listBuy == null)
                continue outer;
            for(int i = 0; i < listBuy.size(); i++) {
                Offer buyOffer = listBuy.get(i);
                //todo - handle exchange
            }
        }
    }

深入研究后,我发现以下行似乎是问题所在:

After looking deeper into this, I found that the following line seems to be the issue:

                Offer buyOffer = listBuy.get(i);

如果我将此行更改为以下内容,它将不再缩短执行时间:

If I change this line to the following, it will no longer cripple execution time:

                Object buyOffer = listBuy.get(i);

因此,当从 listBuy 投射对象时,执行会出现严重延迟.有什么解决办法吗?我难住了.

Therefore, when casting on the object from listBuy there is a major delay in execution. Is there any work around for this? I'm stumped.

提前致谢!

推荐答案

你衡量错了.

当你写Object buyOffer = listBuy.get(i);时,内循环没有副作用,JIT编译器完全消除了循环.

When you write Object buyOffer = listBuy.get(i); the inner loop has no side effects, and JIT compiler eliminates the loop completely.

使用 Offer buyOffer 不允许 JIT 删除循环,因为现在每个列表访问都有可能抛出 ClassCastException 的副作用.

With Offer buyOffer JIT is not allowed to remove the loop, because every list access now has a possible side effect of throwing ClassCastException.

类型检查是一个快速操作,我怀疑它是您应用程序中的瓶颈.很可能算法本身是次优的,因为它具有三次复杂度.

Type check is a fast operation, I doubt that it is a bottleneck in your application. Most likely the algorithm itself is suboptimal since it has a cubic complexity.

这篇关于铸造时 Java 嵌套 Foreach 慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆