String and StringBuffer

xiaoxiao2021-03-06  64

Just saw an article discussed String and StringBuffer, making me more understanding again. Http://community.9cbs.net/expert/topic/2872/2872127.xml Test code is as follows: import java.util.date;

public class TestStringPerformance {static final int MAX_APPEND = 5000; static final int THREAD_SLEEP = 6000; public static void main (String [] args) {long start, end; System.gc (); try {Thread.sleep (THREAD_SLEEP);} Catch (InterruptedException IE) {} start = new date (). gettime (); method1 (); end = new date (). gettime (); system.out.println ("Method1 TOOK" (end-start) "MilliseConds.");

System.gc (); try {thread.sleep;} catch (interruptedException IE) {} start = new date (). Gettime (); method2 (); end = new date (). Gettime (); system .out.println ("Method2 TOOK" "MilliseConds.");

System.gc (); try {thread.sleep;} catch (interruptedException IE) {} start = new date (). Gettime (); method3 (); end = new date (). Gettime (); system .out.println ("Method3 TOOK" "MilliseConds.");

System.gc (); try {thread.sleep;} catch (interruptedException IE) {} start = new date (). Gettime (); method4 (); end = new date (). GetTime (); system .out.println ("Method4 TOOK" "MilliseConds.");} // new keyword, no stringbuffrs static string method1 () {string res = new string (); for (int i = 0 i

DD ")); Break; Case 4: Res. Append (New String (" EE ")); Break;}} Return Res.} ();} // no new keywords, stringbuffer buy static string method4 () {StringBuffer Res = new stringbuffer (); for (int i = 0; i

} Test Results: Method1 Took 901 MilliseConds.Method2 TOOK 811 MilliseConds.Method3 Took 10 MilliseConds.Method4 Took 0 MilliseConds.

Description: Method1 uses new but useless since StringBufferMethod2 does not use newbufferMethod3 to use New, use StringBufferMethod4 without new but use StringBuffer, when you make a large string, we choose StringBuffer to greatly improve performance .

转载请注明原文地址:https://www.9cbs.com/read-111126.html

New Post(0)