0

I'm fairly new to Java and I'm writing an android game - and there's one line of code in a tight loop that's really annoying me.

targetBlocksRemain += letterArray[column][row].isTargetBlock() ? 1 : 0;

I feel like must be possible to write this without the conditional statement and therefore without the potential branch prediction performance hit.

I'll optimise out the tight loop eventually so I'm not massively concerned in the long run, but it'd be nice to know if there's a way to resolve similar situations.

edit Just to clarify - this is a pseudo theoretical questions - there are lots of other things I could do to improve this, such as store isTargetBlock as an int. I'm not really interested in other suggestions, just wondering if there's a way do resolve this particular issue.

edit 2 Hoping to look at what the Dalvik VM is doing shortly to work out how it handles this.

7
  • Is your application running slow? There is a thing called premature optimization Commented Mar 6, 2014 at 9:52
  • @CeilingGecko I'm targeting low end Android devices, and there's no harm in zero cost optimisations as I go along. I didn't come here for a lecture on premature optimisation, I came for an answer. Commented Mar 6, 2014 at 9:56
  • 2
    please have a look at this stackoverflow.com/questions/16868196/… - looks like you should not be concerned about branching! Commented Mar 6, 2014 at 9:56
  • @mkorszun It would be interesting the see the code produced by the compiler on the Dalvik VM. Anyone got any ideas how I'd go about getting that? Commented Mar 6, 2014 at 10:00
  • If you want to see the Dalvik VM code, then you'd need to compile your app, then decompile it into Dalvik Bytecode (or something along those lines) - there's free software that does this for you Commented Mar 6, 2014 at 11:28

1 Answer 1

-1

I know it might not look good but will avoid conditional statement:

do this once in the activity:

HashMap<Boolean, Integer> map=new HashMap<Boolean, Integer>();
map.put(false, 0);
map.put(true, 1);

and in loop

targetBlocksRemain += map.get(letterArray[column][row].isTargetBlock());
Sign up to request clarification or add additional context in comments.

1 Comment

This won't help. It does not avoid a conditional statement at all. To get something out of a HashMap, the key's hashCode method gets called. The hashCode method for a Boolean includes the ternary operator. So this gives you a ternary operator, plus a whole lot of extra stack-juggling stuff associated with the method calls. This is the opposite of an optimisation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.