StringBuffer in the storage of characters, there is an upper limit, once reached the line will be wrong, I encountered a project in the query data from the database, and then write to the local file
, the amount of data is about 300,000, at this time the efficiency is very low. The following is a rough simulation of the program code, project code because it is a bank project, it is not posted out. Look at the approximate analog code.
1 Public classLis {2 3 Public Static voidMain (string[] args)throwsIOException {4File file1 =NewFile ("D:\\io\\out.txt");5BufferedWriter BW =NewBufferedWriter (NewFileWriter (File1));6StringBuffer buffer =NewStringBuffer ("s|1| s0180| | | | ");7 8Buffer.append ("\ r \ n");9 TenList sublist =NewArrayList (); OneList Listid =NewArrayList (); A Longs=System.currenttimemillis (); - //prevent errors that are greater than 10,000, loop processing - for(inti = 0; I < 60; i++) { the for(intI=r; k<5000; k++){ -Buffer.append ("KKKKKKKKKKKKKKKKKKKKKKKKKK" +k); -Buffer.append ("\ r \ n"); - } + Bw.write (buffer.tostring ()); - Bw.flush (); +Buffer =NewStringBuffer (); A } at LongE=System.currenttimemillis (); -System.out.println (E-s); - bw.close (); - } -}
Time line 24th outputs the result to 230~236.
Let's change StringBuffer to Stringbuider.
1 Packagemostest;2 3 ImportJava.io.BufferedWriter;4 ImportJava.io.File;5 ImportJava.io.FileWriter;6 Importjava.io.IOException;7 ImportJava.text.SimpleDateFormat;8 Importjava.util.ArrayList;9 Importjava.util.Date;Ten Importjava.util.List; One A - - Public classLis { the - Public Static voidMain (string[] args)throwsIOException { -File file1 =NewFile ("D:\\io\\out.txt"); -BufferedWriter BW =NewBufferedWriter (NewFileWriter (File1)); + //StringBuffer buffer = new StringBuffer ("s|1| s0180| | | | "); -StringBuilder buffer =NewStringBuilder ("s|1| s0180| | | | "); + ABuffer.append ("\ r \ n"); at -List sublist =NewArrayList (); -List Listid =NewArrayList (); - Longs=System.currenttimemillis (); - //prevent errors that are greater than 10,000, loop processing - for(inti = 0; I < 60; i++) { in for(intk=0; k<5000; k++){ -Buffer.append ("KKKKKKKKKKKKKKKKKKKKKKKKKK" +k); toBuffer.append ("\ r \ n"); + } - Bw.write (buffer.tostring ()); the Bw.flush (); * //buffer = new StringBuffer (); $Buffer =NewStringBuilder ();Panax Notoginseng } - LongE=System.currenttimemillis (); theSystem.out.println (E-s); + bw.close (); A } the}
Time line 24th outputs the result to 222~225.
The results can be seen, the effect of optimization is very obvious, but it should be noted that:
StringBuilder is more efficient than stringbuffer, and if a single thread does not need to consider synchronization issues, you can use StringBuilder to improve efficiency.
Java about the efficiency of StringBuffer and StringBuilder writing files