您現在的位置是:首頁 > 遊戲

在Java程式碼規範中為什麼不能出現System.out.println()

由 抱著地球去旅行 發表于 遊戲2022-01-03
簡介println(“有System

未轉變者怎麼調中文

一般在Java開發的過程中或者除錯bug的時候,很多人都會習慣性的使用System。out。println語句來輸出到控制檯中,來觀察資料或邏輯是否正常。當開發或者除錯完畢後,很可能就忘記刪除,直接就釋出到生產環境中去了。

程式碼感受下

public static void main(String[] args) { long start1 = System。currentTimeMillis(); for(int i=0;i<100000;i++){ System。out。println(“i:”+i); } long end1 = System。currentTimeMillis(); System。out。println(“有System。out。println的耗時:”+(end1-start1)); long start2 = System。currentTimeMillis(); for(int i=0;i<100000;i++){ } long end2 = System。currentTimeMillis(); System。out。println(“無System。out。println的耗時:”+(end2-start2));} 有System。out。println的耗時:408無System。out。println的耗時:0

從控制檯列印的結果我們可以看到,迴圈10w次的列印時間需要耗時408毫秒,沒有列印的迴圈幾乎等於0毫秒。

原理分析

public void println(String x) { synchronized (this) { print(x); newLine(); }}

從System。out。println的原始碼中我們可以看到它在一開始就用synchronized同步鎖給鎖起來了,所以System。out。println是一個同步方法,在高併發的情況下,會嚴重影響效能。

總結

在日常開發或者除錯的過程中,儘量使用log4j2或者logback這些非同步的方法,進行日誌的統一收集,禁止使用System。out。println。專案上線前也要進行全域性搜尋或者程式碼掃描,防止有人誤提交帶有System。out。println的程式碼,從而升級到生產環境而影響效能。

推薦文章