JAVA-String v.s StringBuffer v.s StringBuilder

Sue Chi
Sue Chi
Nov 3 · 2 min read

根據JAVA String class的設計,每一個宣告出來的String object都是immutable(內容不可變更的)。
而為了確保JAVA String的immutability,String class被設定為final class。
如果String class不為final的話,我們就能寫一個subclass去繼承String class繼而去變更String的內容了。

因此當Code中使用大量String操作的時候…
1. 執行時間會較長
2. Memory使用量較高(因為產生了一堆還沒被GC回收的暫時性String…)

範例如下:

執行結果為:

a = TEST123
Identity : 1846274136
a = TE
Identity : 1639705018
a = TE456
Identity : 1627674070

由執行結果可以看出,String a的HashCode三次都不相同,這表示對String a操作三次之後,我們已經在String pool中新增出了三個不同的String literal(TEST123 & TE & TE456)。

至於什麼是String Pool?可以參考如下這篇:
https://www.journaldev.com/797/what-is-java-string-pool

那要如何避免在操作String的時候產生不必要的String垃圾呢?
A:使用StringBuffer或是StringBuilder!
這兩個類別皆為JAVA所提供的mutable String

範例如下:

執行結果為:

aBuilder = TEST123
Identity : 1846274136
aBuilder = TE
Identity : 1846274136
aBuilder = TE456
Identity : 1846274136

aBuilder三次操作結果的HashCode都相同,這表示我們是針對aBuilder去修改內容,並沒有產生其他物件。
至於StringBuffer與StringBuilder的差異則如下表所示:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade