String與StringBuffer的區別

來源:互聯網
上載者:User

標籤:

String:

          是對象不是原始類型.
          為不可變對象,一旦被建立,就不能修改它的值.
          對於已經存在的String對象的修改都是重新建立一個新的對象,然後把新的值儲存進去.
          String 是final類,即不能被繼承.

StringBuffer:
          是一個可變對象,當對他進行修改的時候不會像String那樣重建立立對象
          它只能通過建構函式來建立,
         StringBuffer sb = new StringBuffer();
         對象被建立以後,在記憶體中就會分配記憶體空間,並初始儲存一個null.通過它的append方法向其賦值.

sb.append("hello");

字串串連操作中StringBuffer的效率要明顯比String高:

String對象是不可變對象,每次操作Sting 都會重建立立新的對象來儲存新的值.

StringBuffer對象執行個體化後,只對這一個對象操作。

我這裡寫了一個小的例子,來測試String和StringBuffer在時間和空間使用上的差別。

public class Test {public static void main(String args[]) {String str = "abc";StringBuffer sb = new StringBuffer("abc");Runtime runtime = Runtime.getRuntime();long start = System.currentTimeMillis();long startFreememory = runtime.freeMemory();for (int i = 0; i < 10000; i++) {str += i;//測試StringBuffer時候把注釋開啟//sb.append(i);}long endFreememory = runtime.freeMemory();long end = System.currentTimeMillis();System.out.println("操作耗時:" + (end - start) + "ms," + "記憶體消耗:"+ (startFreememory - endFreememory)/1024 + "KB");}}



測試結果:

使用String做10000次向一字串後添加字串

操作耗時:1872ms,記憶體消耗:1301KB

使用StringBuffer做10000次向一字串後添加字串

操作耗時:15ms,記憶體消耗:162KB

差別顯著!

String與StringBuffer的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.