2

I would like to optimize the below code that is very simple, Do you have any idea?

public void addValueToTab(int _valueToAdd){
    for(int k=0; k < myArray.length; k++){
        myArray[k]+= _valueToAdd;
    }
}

myArray is an int[]

the length of myArray can vary between 50 to 1000.

Thanks a lot for your help,

4
  • 1
    That piece of code seems the fastest way already. Commented Jan 15, 2014 at 3:26
  • Loop unrolling. Counting down rather than up (testing against 0 is faster than testing against other values). Outside of that, you're running up against the limits of the language. Important question: Have you profiled your code and determined that you're spending enough time in these few lines to justify focusing on them rather than on higher-level algorithms? Commented Jan 15, 2014 at 3:26
  • @keshlam i've tested. JIT vectorizes only the simpliest loop, it is really the fastest option Commented Jan 15, 2014 at 8:47
  • Interesting. I keep forgetting that vectorization's now a factor. That re-emphasizes that micro-optimization is usually the wrong place to start, and that any source-code-level optimization needs to be guided and checked with proper profiling tools. Commented Jan 15, 2014 at 13:45

1 Answer 1

5

I'd bet that with a server JVM and hot code, there's nothing you could do to speed it up (since the JVM does all the optimizations already). Especially, myArray.length gets cached in a local variable and the loop gets unrolled several times.

In case you care about performance with a weaker JIT compiler, you could do the two above things manually, but why should you care?

A side note

Interestingly, there's a similar loop where the JVM is pretty loosy:

for (int i = 0; i < value.length; i++) {
    h = 31 * h + val[i];
}

It's not an unimportant piece of code, it's the body of String.hashCode. By unrolling it manually you can get a speedup of factor 2+.

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

1 Comment

Thank you for your help on this one.

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.