簡體   English   中英

這些哪個對性能更好

[英]which one these is better for performance

我正在解決一個問題,我需要盡可能地優化我的代碼。

我有一個循環,需要進行一些計算,並且需要向數組中添加元素以進行進一步的計算:

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;
    }
}

在以下情況中,最好的是:

  1. 使用unit或直接訪問數組(用array[i]替換unit
  2. 使用中間變量或直接計算結果。 例如,刪除n並將其替換為公式
  3. 創建許多方法來分解代碼或將所有計算都放在一種方法中
  1. 沒關系。

  2. 這僅在您在計算中調用函數並多次使用同一表達式時才重要。 在這種情況下,沒關系。

  3. 沒關系。 為了提高可讀性,您可能需要將不同的功能拆分為不同的功能。

編輯:IO通常是瓶頸。 in.nextInt()有什么作用? 您可以將其移出循環嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM