Reputation: 1007
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?
Upvotes: 3
Views: 106
Reputation: 27812
In Java, strings are immutable. So this statement:
temp =temp + line;
creates a new string object for each line in your file, which slows things down. Some better alternatives include StringBuilder and StringBuffer
You can find some benchmarks here that compare the speed of these 3 ways of concatenating strings.
Upvotes: 1
Reputation: 41281
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()
.
Upvotes: 6