What would be the best way to optimize this code below to make it more efficient while applying the ‘best practices’. This is just a simple school project and it works, I’ve tested it. But I just feel like there’s a better and more efficient way to write this method. What do you think?
- I have an array that
is pre-populated with a bunch of
numbers. ThegetMax()method
retrieves the highest number in the
array. But if the array is empty it
returns-1. -
nElems is simply a variable that keep tracks of how many elements are present in the array.
-
arrayis the private array declared at the beginning of the class.public int getMax() { int k = 0; int max = array[0]; for(int j=0; j<nElems; j++) { if(max < array[j]) max = array[j]; } if(k == nElems) return -1; else return max; } // end of method
Oh and what should I name my k variable to make it more readable? Its purpose is to be 0, so it could be checked against the number of elements in an array to return either -1 or highest number;
Assume all array values are positive.
Zero doesn’t need a name – if you mean 0, use the literal
0.Your loop is fine. There are things you could do to try to optimise it, but they won’t necessarily help. Almost always you may as well just leave such localised, “keyhole” optimisation to the JIT. If you just want to try a few things as a learning exercise, then you could experiment as follows:
numElemisn’t a multiple of the number of times you’re unrolling.Integer.MAX_VALUE. You aren’t going to find anything bigger. It’s difficult to define the performance effect of this, since it will speed it up for large arrays with a MAX_VALUE that isn’t too near the end, but most likely slow it down for everything else. It might be interesting to see how much difference it makes, though.I’m not saying any of these will make a difference, faster or slower, but they could. So run them and time how fast each goes. What you’ll most likely learn, is that compared with leaving it to the JIT this stuff isn’t worth your time. But you never know 😉
The surrounding code can be cleaned up, though, to make it more comprehensible rather than to make it faster. For example:
This also removes the error in your code, that if the array is size 0, then you access out of bounds in the second line. ColinD’s way of doing that is just as good, I’m showing something different for the sake of variety.
Here’s the shorter code assuming all values are non-negative: