Practice pieces
Efficency
To manage this task, you need to first understand what the core behaviour of the program is, and then edit down to that. Essentially the program:
- Gets the start time.
- Makes an array full of random ints.
- Prints out the sum of these ints.
- Gets the end time and prints how long the program has taken.
Hints:
Here's some of the efficency issues you could sort out for this:
- Accidentally looping through arrays you're already looping through - for example calling a procedure inside a loop to find something, and then having that procedure loop through the array to find it. You might do this accidentally if you reuse a method.
- Calling methods inside very large data loops (method calls are quite expensive).
- Using if-statements inside very large data loops (again, expensive -- the less the better, though likely as not you'll need some sometimes).
- Making variables inside loops instead of outside them, so they keep getting recreated.
- Unnecessary casting because the data storage variable is of the wrong type.
- You can actually save a little time by having a variable hold the second array dimension length if the array is a regular array, rather than calculating it for each row, though it impacts clarity and isn't usually needed.
- Looping twice through an array to fill and analyse it separately when the algorithm allows you to do both together (in general, though, only do this went it is slowing the program -- again, merging reduces clarity).
- Printing inside a loop -- this takes a massive amount of time; indeed, printing to the screen during runs is generally only advisable when debugging. You can reduce the number of prints by using mod ("
%
"; remainder), e.g.:
if (i%100 == 0) System.out.println(etc);
- Looping until the end of loops when they could be broken out of early.
- Using AND statements, but not using the "shortcut" AND
operator
&&
(which doesn't assess the second clause if the first is false).
Other inefficiencies not present include:
- Putting low-probability if-statements early in an if-else ladder.
- Using if-else ladders where a switch/case statement might be better.
- Using array-replacement objects, rather than arrays.
- Making arrays too large for RAM memory.
- Reading and writing from the harddrive.
Give it a go and see if you can get it working faster. Making the changes above reduced it from 21659 milliseconds to 7 for me.
If you need more help, here's the answer (or one option, anyhow).