简体   繁体   中英

which one these is better for performance

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:

  1. Use unit or access the array directly (replacing unit with array[i] )
  2. Use intermediate variables or calculate the result directly. For example, removing n and replacing it with it's formula
  3. Create many methods to break down code or put all the calculations in one method
  1. This does not matter.

  2. This only matters if you call functions in your calculations and use the same expression multiple times. In this case, it does not matter.

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM