This article mainly introduces relevant information and detailed examples of the difference between String and StringBuffer in Java. A small example is used to test the difference in time and space usage between String and StringBuffer. Friends in need can refer to it
Detailed examples of the difference between String and StringBuffer in java
String:
It is an immutable object. Once it is created, its value cannot be modified.
Any modification to an existing String object involves re-creating a new object and then saving the new value in it.
string is the final class, that is, it cannot be inherited. , when it is modified, the object will not be re-established like String.
It can only be created through the constructor,
StringBuffer sb = new StringBuffer();
String object is an immutable object. Every time Sting is operated, a new object will be re-created to save the new value. After the StringBuffer object is instantiated, only this An object operation.
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"); } }
The operation takes: 15ms, memory consumption: 162KB
The above is the detailed content of The connection and difference between String and StringBuffer in java. For more information, please follow other related articles on the PHP Chinese website!