Re: Reading strings using BufferedReader.readLine() is too slow
- From: Roedy Green <see_website@xxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 28 Jun 2007 18:53:17 GMT
On Thu, 28 Jun 2007 06:13:46 -0700, wicli_pucli@xxxxxxxxxxx wrote,
quoted or indirectly quoted someone who said :
reply = new String();
String reply_now;
while ((reply_now = in.readLine()) != null) {
reply += reply_now;
}
You are allocating objects like mad here, cause excess gc.
first use:
reply = "";
rather than new String();
new String() should almost never be used.
see http://mindprod.com/jgloss/string.html
use code like this instead for much greater efficiency
StringBuilder accum = new StringBuilder ( ESTIMATEDTOTALSIZE );
String line;
while ((line = in.readLine()) != null) {
accum.append(line);
}
String result = accum.toString();
However even that improved code is silly. Why do all the work of
splitting the file into lines, then glue them all back together again?
Why not read the entire file in one fell swoop (one physical i/o).
Read the entire file into a byte[] array then convert it to a String,
which is what com.mindprod.hunkio.HunkIO.readEntireFile does for a
living.
see http://mindprod.com/products1.html#HUNKIO
/**
* Get all text in a file.
*
* @param fromFile file where to get the text.
*
* @return all the text in the File.
*
* @throws IOException when cannot access file.
* @noinspection WeakerAccess
*/
public static String readEntireFile( File fromFile ) throws
IOException
--
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
.
- References:
- Reading strings using BufferedReader.readLine() is too slow
- From: wicli_pucli
- Reading strings using BufferedReader.readLine() is too slow
- Prev by Date: problem with JDBC connection
- Next by Date: Re: File Reading
- Previous by thread: Re: Reading strings using BufferedReader.readLine() is too slow
- Next by thread: Re: Reading strings using BufferedReader.readLine() is too slow
- Index(es):
Relevant Pages
|
|