Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

large difference in execution speed during file read

Tags:

java

file

Can anyone explain why is this happening? The filesize is up to 2MB. It takes less than 2 seconds for the code to execute.

try {
    while ((line = br.readLine()) != null) {
        System.out.println(line);
}
catch(Exception e)
{           
}

But when I change the code to:

String temp = "";
try {
    while ((line = br.readLine()) != null) {
        temp =temp + line;
}
catch(Exception e)
{
}

I understand it would take comparatively more time but it takes the massive time of 470 seconds. Why this difference?

like image 776
John Snow Avatar asked Sep 14 '26 05:09

John Snow


1 Answers

temp =temp + line;

Is concatenation of a string as-is. The concatenation requires that a new string object is created and possibly interned, taking a lot of time. Instead, think about using a StringBuilder in most cases or StringBuffer where synchronization is needed.

Create it once with

StringBuilder sb=new StringBuilder()

and append with:

sb.append(line);

You can then grab the data with sb.toString().

like image 106
nanofarad Avatar answered Sep 16 '26 20:09

nanofarad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!