String vs StringBuffer in JAVA

SITUATION:In this present world,the performance of any application is very important and it’s then only when factors like RUNNING TIME and MEMORY occupied plays very critical role in deciding that factor.While working on one such deliverable i too came accross such condition where i need to read some million odd files and each containing some million odd records and do some operation on the data and overwrite or make a copy of the updated info and show to the user so i used STRINGS approach as any nooby will use and what i came accross was that it was taking almost like an hour to do it so i just being guided by seniors to use StringBuffer class instead of String.When i ran it after making the required changes it took only like 3-4 seconds which was like a miracle.Now that really makes a lot of difference and made me to get the details why did it happen and stuff and share it with everyone.

MECHANISM: So the reason why it happened was that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.So what it means is that whenever u create any string object and assign any value on it and do any operation on it and try to update it,what it does is create a new String object and assign the updated value and doesnt assign it the previous one.So what was happening that for every file and every updation an object was being created in background so in all 1,000,000*1,000,000 many objects were created which was causing that much time to do whole process whereas what happens in StringBuffer is when u do any operation on an object then it will upadate it then and there only without taking any time

Finally, whats the difference between StringBuffer and StringBuilder?

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence ofsynchronization.

Leave a comment