[英]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;
}
}
在以下情況中,最好的是:
unit
或直接訪問數組(用array[i]
替換unit
) n
並將其替換為公式 沒關系。
這僅在您在計算中調用函數並多次使用同一表達式時才重要。 在這種情況下,沒關系。
沒關系。 為了提高可讀性,您可能需要將不同的功能拆分為不同的功能。
編輯:IO通常是瓶頸。 in.nextInt()有什么作用? 您可以將其移出循環嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.