StringBuilder 或 StringBuffer

Java 1.4 或之前版本的 StringBuffer,和 5.0 版的 StringBuffer、StringBuilder 都是直接繼承自 java.lang.Object 類別。它們的作用如剛才提到的,都是為了避免字串的連接或修改時產生許多的暫存字串 (temporary strings)。但在 J2SE Documentaion 1.4.2、5.0 中都提到,StringBuffer 在多執行緒 (multiple threads) 下是安全的 (thread-safe),亦即該類別下的 method 會視需要鎖定,或稱為同步化 (synchronized) 資料處理,亦即保護程式碼不會被分割執行,多個 thread 物件會照應有順序交互執行,避免執行結果的不一致。亦即一次只有一個 thread 可以修改 StringBuffer 實體的狀態,無論你在何時修改 StringBuffer,都不用擔心會有其它的執行緒出現,中斷你正在執行的工作,而毀損了字串資料 [1],[4]:
String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

 而 Java 5.0 新推出的 StringBuilder 可與 StringBuffer 相容,但不應用在同步 (synchronization) 或多重執行緒的情況。但據 Documentation 和某書 [2] 的說法,若是在單一執行緒的環境下,或一段你不擔心會有多個執行緒存取的程式碼中,或是不需同步處理的情況下,就應該儘可能地以新的 StringBuilder 替換 StringBuffer,因為在大多數的情況下,前者的運作速度都比後者要快。版工猜若非 synchronized 的話,應該也可省去一些 overhead。且聽說過去在 StringBuffer上看過的 method 在 StringBuilder 上都有,所以直接對舊有的程式碼作搜尋與替換,原則上不會有編譯上的問題 [2]。
 
本篇發表於 java。將永久鏈結加入書籤。

發表留言