I'm solving a problem and I need to optimize my code as much as possible.
I have a loop in which I need to do some calculation and I need to add an element to an array for further calculation:
for (int i = 0; i < lightCount; i++) {
int dis = in.nextInt();
int dur = in.nextInt();
double unit = distance / duration * 3.6;
array[i] = unit;
if (speed < unit) {
double n = unit / (2 * speed);
if (!((n - (int) n) == 0))
n = n + 1;
int tmp = (int) (unit / (2 * (int) n));
if (tmp < answer)
answer = tmp;
}
}
Which is the best of the following situations:
unit
or access the array directly (replacing unit
with array[i]
) n
and replacing it with it's formula This does not matter.
This only matters if you call functions in your calculations and use the same expression multiple times. In this case, it does not matter.
This does not matter. For readability, you might want to split different functionality into different functions.
EDIT: IO is often the bottleneck. What does in.nextInt() do? Can you move it outside of the loop?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.