hi, i am appending a string using Stringbuffer sb = new StringBuffer(); method 1: sb.append("name=" + name); sb.append("age=" + age); sb.append("addres=" + address); method 2: sb.append("name="); sb.append(name); sb.append("age="); sb.append(age); sb.append("addres="); sb.append(address); Is method 2 better than method 1 ?? I suppose yes as in method one first it will do a string concat and then do a append of string buffer am i right ?? any comments TIA Anil
Heck if we're looking for simple: Stringbuffer sb = new StringBuffer("name=" + name + "age=" + age + "address=" + address); Of course if optimization is not your concern then I'd choose #1. And to make it more readable: String name = "name=" + name; String age = "age=" + age; String address = "address=" + address; sb.append(name + age + address);
posted 17 years ago
hi, But will it affect the performance if i am adding so much of data and that too if this code comes inside a loop. Is it going to affect the performance too much ?? Regards Anil
The best way to proceed is to write code that is simpler to understand and easier to maintain. Later, when you are optimizing, and your profiling tools have shown a significant bottleneck in a particular loop, then you can worry about these litle issues and make any necessary changes for increased performance. But it's not a very efficient use of your time to worry about how efficient each line of code you write is. Worry more about readability and style. You're not writing an assembly language program for an 8 bit machine with 16K of memory and a 2Hz. CPU, so relax and don't worry so much if a concatenation is a performance hit.
Ten, twenty, thirty years ago storage space (cards, paper tape, etc) as well as processor speed was much more precious than it is now. Now, readability and ease of use is far more important.
JavaBeginnersFaq "Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
posted 17 years ago
Thanks for your useful comments. Acutally i wrote a code to test it. and found not much difference between the two. For about 20000 loops i got this result method 2 total time in ms 210 method 2 total time in ms 140 thanks Anil
He baked a muffin that stole my car! And this tiny ad: