前言
開發過程中在代碼加入合理日誌記錄是非常重要的,經常會在代碼中看見循環語句裏面出現日誌記錄。
問題
在循壞中加入日誌是否合理?
如果在導入百萬級數據或者億級數據是否會對性能產生影響呢?
如果有興趣瞭解,不妨我們一起進入代碼實驗室來看一看
案列
/**
* log日誌耗時順帶System.out.println
*
* @author 熊貓程序猿
* @date 2020年1月16日
*/
@Slf4j
public class Demo {
public static void main(String[] args) {
int count = 1_0000;
long a = System.currentTimeMillis();
a(count);
a = System.currentTimeMillis() - a;
long b = System.currentTimeMillis();
b(count);
b = System.currentTimeMillis() - b;
long c = System.currentTimeMillis();
c(count);
c = System.currentTimeMillis() - c;
System.out.println("循壞耗時:" + a);
System.out.println("log循壞耗時:" + b);
System.out.println("out循壞耗時:" + c);
}
private static void a(int count) {
ArrayList list = Lists.newArrayList();
for (int i = 0; i < count; i++) {
list.add(i);
}
}
private static void b(int count) {
ArrayList list = Lists.newArrayList();
for (int i = 0; i < count; i++) {
list.add(i);
log.info(list.size() + "");
}
}
private static void c(int count) {
ArrayList list = Lists.newArrayList();
for (int i = 0; i < count; i++) {
list.add(i);
System.out.println(list.size());
}
}
}
分析
1萬循壞:
十萬循環:
百萬循環:
千萬循環:
一億循環:
總結
循環次數 | 循環耗時 | log循環耗時 | out循環耗時 |
---|---|---|---|
1萬 | 5 | 76 | 52 |
十萬 | 13 | 923 | 477 |
百萬 | 40 | 4602 | 3269 |
千萬 | 3001 | 26828 | 29777 |
一億 | 41742 | 355691 | 356253 |
由上可得:
應該儘量避免在循壞中打印日誌。
先贊後看,養成習慣,歡迎收看一個行走的熊貓程序猿,下期再見