2

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);

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.

Thanks in advance!

4
  • 3
    Those casts don't happen directly in front of you, and I legitimately doubt that the cast is what's slowing you down as opposed to the triple-nested loop you're running. Commented Oct 17, 2015 at 15:41
  • Why are you switching from foreach loop (for(Offer sellOffer : listSell)) to plain for loop (for (int i=0; i<listBuy.size(); i++))? Why not use foreach on the third loop too? Commented Oct 17, 2015 at 15:54
  • Loop label (outer) is discouraged, and should only be used where needed. You don't need it, because using break will get you same result. Commented Oct 17, 2015 at 15:56
  • Thanks @Andreas for the outer tip. Also I was using the plain loop simply to test the cast theory. Commented Oct 17, 2015 at 16:04

1 Answer 1

3

You measure it wrong.

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

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.