tags:

views:

81

answers:

6

Java.

I have a very small int array (4 elements).

What's the fastest way to get max value? All values will be between 0 and 255.

Also int array is faster than byte array? Is casting much of a hit?

What's the fastest way to get sum of all values?

The reason I ask is cause this is a major bottleneck in a program I inherited. They aren't slow per say, but the guy is calling these methods many many times and it adds up. Eventually I need to rewrite the entire thing, but looking for some quick tricks to speed this up in the short term.

+2  A: 

If you are:

  • iterating the array once
  • using only primitive types (not wrappers)

Then look somewhere else for performance problems.

Bozho
+1  A: 

Fastest way to get sum of 4 values is sum = a[0] + a[1] + a[2] + a[3]

Sagar V
he wants max, not sum
Bozho
he does need the sum also. Look at the last question.
Sagar V
hm.. correct. I'm not sure that this isn't a mistake of his, though.
Bozho
Could be. Anyway I just realized if he wants sum and max both he can do both in a single for loop.
Sagar V
+3  A: 

Here's my go at it... basically an unrolled loop. The JIT would probably have recognized that a loop would have gone from 0 to 3 and unrolled it itself anyway, but who knows...

public static int max(int[] a) {
    int max = a[0] > a[1] ? a[0] : a[1];
    max = a[2] > max ? a[2] : max;
    return a[3] > max ? a[3] : max;
}

Sum would obviously just be a[0] + a[1] + a[2] + a[3].


You could also try packing the four 0-255 values in an int, and do some bit-operations instead.

aioobe
+2  A: 

What's the fastest way to get max value? All values will be between 0 and 255.

Getting the maximum logically requires looking at (and comparing) each value at least once, so the straightforward way (take first element, compare with each and keep the larger one) is pretty much optimal.

Also int array is faster than byte array? Is casting much of a hit?

Could make a difference. Hard to say for sure. Benchmark and/or profile.

What's the fastest way to get sum of all values?

Again the straightforward way.

Overall it sounds like the biggest potential speed gain in your case is not optimizing the apparently very simple operations on this array, but finding a way to reduce the number of times they are performed.

Michael Borgwardt
+2  A: 

If the values in the array don't change often but the max is required very frequently then it might be beneficial to cache the maximum value instead of calculating it every time.

Qwerky
+1  A: 

I would recommend using a custom class wrapping the array. This class can calculate both the max, and the sum right at the time of setting the data, and then cache it. If the data is to be changed later on, the cache would also be updated.

This is, of course, assuming that the need to obtain the max and sum is much more often than the need to change the data.

Aditya Jha