large difference in execution speed during file read
file, java
Solution
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()`.
Problem
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?