Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

is StringBuffer.append("c1").append("c2") faster ? than spli

Status
Not open for further replies.

remyvrs

Programmer
Jul 12, 2005
66
0
0
RO
I am in kind of a dilema:
is there a reason to think that this section:

StringBuffer sb = new StringBuffer(100);
sb.append("abc").append("def").append("ghi");


works faster than this one:

StringBuffer sb = new StringBuffer(100);
sb.append("abc");
sb.append("def");
sb.append("ghi");


It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
As it is a mutable object, I don't see any reason to think one is faster than another.

I even bet the compiler will produce the same bytecodes.

Cheers,
Dian
 
Btw, want to make that faster? Just use +

StringBuffer sb = new StringBuffer("abc"+"def"+"ghi");

Cheers,
Dian
 
Actually that is not al all a good way beacouse it what i want not to use :
Creating 3 String objects at first then a concatenation between the first 2 which creates another String object and then another concatenation.
That is one of the main reasons StringBuffer was created because creating a String or concatenating is not all fast code.

It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
That is one of the main reasons StringBuffer was created because creating a String or concatenating is not all fast code.

That entirely on the size of the String objects you are using. If they are small Strings (like your example), then saying :

String s = "abc" +"def" +"ghi";

will be a lot quicker than using a StringBuffer.
But if you have large Strings (ie hundreds/thousands of characters), then a StringBuffer is more optimized.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
sedj please mark this thread for notification because when i'll have time i'm gonna test what you have said!

P.S: as i remember i have tested and i remember that what you have said is not true but i want to double -check before telling that i'm sure.


It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
Please check this link out sedj!

I understand that when you make a concatenation like "abc"+"def" there is created an StringBuffer object in which it appends the "abc" and "def" values and then the result is written in the result String


It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
Well try running this code ... it proves that String concat is quicker than StringBuffer by FAR when concatenating SMALL Strings :

My results :

Code:
C:\java>java Test
String concat : 15 millis
StringBuffer append : 6844 millis

C:\java>java Test
String concat : 16 millis
StringBuffer append : 6797 millis

C:\java>java Test
String concat : 16 millis
StringBuffer append : 6828 millis

Code:
class Test {

 	public static void main(String args[]) throws Exception {
		long start = System.currentTimeMillis();
		for (int i = 0; i < 10000000; i++) {
			String s = "abc" +"def" +"ghi";
		}

		long end = System.currentTimeMillis() - start;

		System.out.println("String concat : " +end +" millis");

		start = System.currentTimeMillis();
		for (int i = 0; i < 10000000; i++) {
			StringBuffer sb = new StringBuffer();
			sb.append("abc");
			sb.append("def");
			sb.append("ghi");
			String s = sb.toString();
		}

		end = System.currentTimeMillis() - start;

		System.out.println("StringBuffer append : " +end +" millis");
	}
}

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
When you concatenate constans Strings like "abc" + "def", the concatenations is done at compilation time, so in the bytecodes there will be a "abcdef" String that will involve no execution time.

In any other cases, StringBuffer is faster if it's correctly initalized.

More information:

Timing test:
Cheers,
Dian
 
Well thats the question isn't it - are the values hardcoded or not ? The examples so far have been - so if you are performing operations where the values are known, then using a String concat is going to beat a StringBuffer hands down, but if the values are dynamic, the timings are different, and String concat slows down.

Basically, optimization depends on the case - for hardcoded values like the OP, then String concat should be used, but if the Strings are large and dynamic, then StringBuffer should be.

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Bottom line: String concat is slower than StringBuffer.append() with 10-20% when using small values and with a factor (10-20-100) when using large values. Of course we are talking about dynamic values , I wouldn't be an idiot to write s = "abc" + "def".
So if you really want to test you should use this code:
Code:
class Test {

     public static void main(String args[]) throws Exception {
        long start;
        String A = "abc";
        String B = "def";
        String C = "ghi";

        start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            String s= "";
            // 1
            //s = String.valueOf(i)+String.valueOf(i)+String.valueOf(i);

            // 2 	
            //s = A+B+C;

            // 3 
            //s += A; s+=B; s+=C;
        }
        long end = System.currentTimeMillis() - start;
        System.out.println("String concat : " +end +" millis");



        start = System.currentTimeMillis();
        for (int i = 0; i < 10000000; i++) {
            StringBuffer sb = new StringBuffer(40);
            //1 
            //sb.append(String.valueOf(i));sb.append(String.valueOf(i));sb.append(String.valueOf(i));

            //2
            //sb.append(A+B+C);	    

            //3
            //sb.append(A);sb.append(B);sb.append(C);

            sb.toString();
        }
        end = System.currentTimeMillis() - start;

        System.out.println("StringBuffer append : " +end +" millis");
    }
}
So if I may say the Test that you made was wrong becouse:
s = "abc"+"def"+"ghi";
is equivalent to
sb.append("abc"+"def"+"ghi");
not at all to
sb.append("abc").append("def").append("ghi");
which is like
s += "abc"; s+="def" ; s+="ghi" (actually another order).
By the way :
it is not fair to put the code
"String s = sb.toString();"
instood of simply sb.toString(); which only acces the method and does not create the object s beside the real result returned by the function.

It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
I wouldn't be an idiot to write s = "abc" + "def".

I do it almost everyday to define set of constants, so it makes sense for me

@sedj: You're cheating :p

1.- Initalize the correct size of the StringBuffer. If you just put new StringBuffer() it's internally resizing for each append() so it's slower.

2.- Try with new String("abc") instead of "abc" , that will simulate dynamic Strings

With these two things, and even with small Strings, StringBuffer r00lz!

Cheers,
Dian
 
bah ! If you can't *massage* the results a little to prove a point (even if it might be wrong-ish) then what can you do ?!

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
You choose the wrong guy then, some people call me the StringBuffer paladine!

Cheers,
Dian
 
I know that I expressed it in a bad way but I meant that I wouldn't use
s="abc"+"def" if i would think that it is operated at each execution. I wanted to power the fact that there is no operation done in the first Test comparing to the two append's of stringbuffer.

And the link's posted upper in this thread explain very well why StringBuffer works faster then String and much more : link that Diancecht posted refers exactly to the mistakes made in the first Test.
Not even the Tests that I made are perfect but there you can see that StringBuffer works faster even with small Strings.
And for large String ... just put the initialization outside the iteration and you will see a big-big difference!!!
That's why if you want optimal code you should use StringBuffer like Diancecht does and sedj should admit that he was wrong!

It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
Anyway, as stefan said once: If you need a zillion iterations and a long thread to discuss which option is better, code as you want, because no one will ever notice the difference.

Cheers,
Dian
 
Believe or not in my case it makes a difference: in a jsp i build an StringBuffer with 1000 up to 100.000 characters by getting data from the database. When going up over 10.000-20.000 it makes a big difference (StringBuffer 1-3 secs String ... up to one minute).
But even at small operation I should use StringBuffer because there is a Quality Office in the company that I work for that gives us notes for the quality of the code which counts for the income.
As i said get the initilization outside the iteration and you will see a great difference.

It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
This thread seems to be about what is called 'premature optimisation'.

Who cares if one method is faster than the other? You should write your code to be correct. If you later find that it does not meet your specification for speed, then you should profile your program to find out where it's spending most of its execution time and then find a faster way to achieve that part of the program.

The above micro-optimisation is usually pointless without knowing the run-time characteristics of your program. You'll usually find the design/architecture/algorithms to be the source of bottlenecks rather than specific methods of concatenating strings etc.
 
And after I spent two weeks or up to 6 months writing a page that is not accepted by my client beause it is slow i should retake all the code and see every portion to see if it is slow or it can be improved.
I think microserf is wrong because it is a matter of guideline:
If I know it works faster I write it the first time in the best way I know.
The project I'm involved in has thousands of classes written and they are slow because guys like you thought that little things don't matter and now we are suffering the consequincis doing (recorecting) what they should have done the first time and get salary penalities until the pages go for standards of 500 miliseconds.
There is no such 'premature optimization'...just imature programmers. What do you mean?... I know from the beggining why the code sucks and is slow and I still should use the bad way...
The point is : for concatenation:
...StringBuffer r00lz!...

It's nice to be important but it's more important to be nice.
Thanks for your attitude!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top