| 方法 | 程式碼關鍵 | 1MB 檔案耗時 (秒) | 倍數差異 |
|---|---|---|---|
| 1. FileInputStream.read() | 逐位元組讀取 | 6.9 | 基準 |
| 2. BufferedInputStream.read() | 8KB 緩衝 | 0.9 | 7.7x |
| 3. 自行緩衝 byte[2048] | fis.read(buf) | 0.4 | 17x |
| 4. 一次性讀全檔 | byte[len] = new byte[file.length()] | 最快 | 記憶體風險 |
方法 2 為最佳平衡點;方法 3 需自行處理邊界,維護成本高。
System.out 預設行緩衝,互動式必要。new PrintStream(new BufferedOutputStream(fdout, 1024), false),速度提升 3 倍。DataInputStream.readLine() 已棄用,無法正確轉碼 Unicode。BufferedReader.readLine() (Reader 體系),速度快 20% 且支援完整字元集。| 方式 | 範例 | 25000 次耗時 (秒) |
|---|---|---|
| 固定字串 | print("The square of 5 is 25\n") | 1.3 |
| 字串串接 | print("The square of " + n + " is " + n*n + "\n") | 1.8 |
| MessageFormat (預編譯) | fmt.format(values) | 7.8 |
| MessageFormat.format 靜態方法 | MessageFormat.format(pattern, values) | 10.4 |
國際化場景不可避免,但需意識到效能開銷。
RandomAccessFile.seek() 開銷大,解法:在 RandomAccessFile 上建立應用層緩衝區 (如 4KB),按區塊讀取,區塊內直接定位,適合二分搜尋等局部性存取。
java.util.zip 提供 ZipOutputStream/InputStream。ArrayList:隨機存取 O(1),記憶體受限。StreamTokenizer 方便但較慢 (內部按雙位元組處理)。ObjectOutputStream 通用但慢 (含類描述、物件圖)。DataOutputStream 自定二進位格式,或特定領域編碼 (如位圖)。File.length()、isDirectory() 等需呼叫作業系統,開銷大,避免重複呼叫;遞迴掃描檔案系統時尤為明顯。