aspose file tools*
The moose likes Performance and the fly likes Performance Impact  String vs StringBuilder Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Performance
Bookmark "Performance Impact  String vs StringBuilder" Watch "Performance Impact  String vs StringBuilder" New topic
Author

Performance Impact String vs StringBuilder

Steven Rodeo
Ranch Hand

Joined: Mar 06, 2008
Posts: 72
Which is more efficient ( Apart from the Number of lines of code <img class="emoticon" src="images/emoticons/cool.gif" border="0" alt="" /> , does one create more String Objects than the other,
if its a multi-threaded program, does one consume more memory than the other. Please Advice

//email uid validity.

StringBuilder sb = new StringBuilder();
sb.append("http://");
sb.append(user);
sb.append("@");
sb.append(host);
sb.append("/");
sb.append(encoding);
sb.append(";POST=");
sb.append(decoding);
sb.append("/;SID=");

System.out.println( sb.toString() );



versus

String httpReq = "http://" + user + "@" + host + "/" + encoding + ";POST=" + decoding + "/;SID=";
System.out.println( "... The HTTP Request ..." httpReq);



Thanks Much
_ddt
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30764
    
156

Steven,
The StringBuilder one is slightly more efficient and uses less memory. In practice, it is unlikely to make enough of a difference to matter either way.

[edited to fix typo]
[ March 11, 2008: Message edited by: Jeanne Boyarsky ]

[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

This is a classic premature optimization.
Its also why there is a Formatter object in Java, so you can write generalized code to do the parameter substitution.

There are far more important things to worry about.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by Pat Farrell:
This is a classic premature optimization.


You don't know this, as the original poster has not told us the context. If the code is executed millions of times, the optimisation could be worthwhile.

I agree with your sentiment, though. Mostly, these things don't have any noticeable effect and simply distract from more-important considerations, like correct operation and readable code.


Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jeanne Boyarsky:
Steven,
The StringBuilder one is slightly more efficient and uses less memory. In practice, it is unlikely to make enough of a difference to matter either way.


That is, in fact, not true. As far as I know, every (post Java 4) compiler will compile the expression



to



- which certainly shouldn't be slower than writing virtually the same code manually.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

Originally posted by Peter Chase:
You don't know this, as the original poster has not told us the context.


Yes, you are correct. I bet a non-trivial amount of money that the context will show that this is a premature optimization.

And as an example, it ignores the fundamental process of compiler and JVM improvements, that each succeeding version does a better job at recognizing equivalent constructs, and generates the same optimization for them. Thus as time goes forward, trivial differences merge towards being unmeasurable, and then they go away.
Jeanne Boyarsky
author & internet detective
Marshal

Joined: May 26, 2003
Posts: 30764
    
156

Originally posted by Ilja Preuss:
That is, in fact, not true. As far as I know, every (post Java 4) compiler will compile the expression

Interesting. Forums are nice. If you post something not true, someone tells you!
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Jeanne Boyarsky:

Interesting. Forums are nice. If you post something not true, someone tells you!



Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
Originally posted by Ilja Preuss:
   


Oh, yes yes yes ! And PC taking on PF in a performance forum. This is gonna be Fun, Fun Fun ! till daddy takes the T-Bird away !

This I gotta see.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18669
    
    8

From the other end of the performance scale, I'm still trying to decide which of the two versions is more readable. I think both of the versions in the original example are equally ugly and unreadable (and no, I don't have a better idea). But if the text fragments being agglomerated included escaped quotes and apostrophes, I think I would find the StringBuilder version more readable than the a+b+c version. Any opinions?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Personally I find the version using + to be more readable, even if it has escaped quotes. But I suppose that's an acquired taste. Concatenation and escapes are so common in Java, I get used to reading stuff written that way.


"I'm not back." - Bill Harding, Twister
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
Context is MT - coding style is flattened by compiler. Context becomes ( possibly ) readable code. Classic premature optimization issue resolves on whether one or the other facilitates correctness for coder by reducing lost details such as unescaped backspace in regex's and so on.

[Jeanne Boyarsky:]   Interesting. Forums are nice. If you post something not true, someone tells you!

Plural of forum is fora.

[Paul Clapham:]   I'm still trying to decide which of the two versions is more readable.

Read Reliability is what the coder can read. Poster asks does one create more String Objects than the other, the answer to which is no. Poster also asks: does one consume more memory than the other The answer to which is premature optimization, unless this is a core loop on a time - intensive / heavy - workload application, in which case both approaches should be harnessed in a profiler and decision made on that.
[ March 14, 2008: Message edited by: Nicholas Jordan ]
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

Originally posted by Jim Yingst:
Personally I find the version using + to be more readable, even if it has escaped quotes. .


Its a personal style thing, I generally like + for string concat, but dislike them when you have to mangle escapes and funky characters. Some of this may just be my personal exposure to trying to internationalize copy. Its really hard to do other languages with all the ""@"\" stuff.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
What about
steve souza
Ranch Hand

Joined: Jun 26, 2002
Posts: 861
<<ats fine but why adding the records in batches adds to performance? Any particular reason for this?? >>
There is probably no one answer for all backends and jdbc drivers. I have tested this with sybase as a backend. In general with batches there is less work and less network IO.

For example if you commit (even if the commit is implicit) after each row the server must do its overhead for committing and communicate this information back to the client once for each row. If this work is done once per batch vs once per row it is less work on server, client, and network. Performance differences can be significant.

I would suggest you do a test in your environment and measure to see if it makes a difference for you. Post the results too.


http://www.jamonapi.com/ - a fast, free open source performance tuning api.
JavaRanch Performance FAQ
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
Steven, are you following this ?
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[B][Ilja]: What about
[/B]

It's slower than using either + concatenation or a StringBuilder. But like most performance issues, that really doesn't matter most of the time . In terms of readability, I think it's just slightly less readable in this particular example, but often it works out to be more readable. And of course it depends on how familiar the programmer is with format specifiers.
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
What about:


By passing the matter to the server where code path analysis should be commonplace and well understood, we can contemplate new syntax coloring schemes.
steve souza
Ranch Hand

Joined: Jun 26, 2002
Posts: 861
I posted to the wrong thread.
Jose Monzon
Greenhorn

Joined: Jun 05, 2008
Posts: 8
Originally posted by Pat Farrell:
This is a classic premature optimization.


And what does that expression exactly mean to you?
.- That you should wait until you have problems with performance before going to your code trying to optimize it, otherwise you don't change anything ?
.- Or after you finish coding your software and it works, you go through thousands of lines looking for ways to optimize it?

It looks like you meant that one shouldn't worry about this unless you have problems with the performance.
steve souza
Ranch Hand

Joined: Jun 26, 2002
Posts: 861
<<It looks like you meant that one shouldn't worry about this unless you have problems with the performance.>>
Correct. A full quote that is well known in p&t circles is: "premature optimization is the root of all evil". google it to read more about the concept.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

Originally posted by Jose Monzon:
It looks like you meant that one shouldn't worry about this unless you have problems with the performance.


Exactly. Get it working first. Write clean code that is easy to understand.
If the system is slow once it works, instrument it. You don't need to be as crude as zillions of printf statements, Netbeans and Eclipse have nice performance tools built in.

Find where it is slow, look in more detail, find the 1% of the code that is causing the slowness. Fix that, ignore all the other possible optimizations.

I have found that I can always, *always*, improve performance by 50%. I can do it as many times as needed. But worrying about performance before it works is a wasted effort.

For one thing, the PHB will change the specs before you get it finished, so you may prematurely optimize code that is thrown away with the PHB's changes.
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
Get some code working first, then do not wait for problems. Optomization sometimes is in the form of making the codebase more readable or understandable. Small, tight code should only be done on areas found by a profiler. Many code tools are well known and available for free - just google your way along on the matter.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Pat Farrell:

I have found that I can always, *always*, improve performance by 50%. I can do it as many times as needed. But worrying about performance before it works is a wasted effort.


+1

I once improved the performance of an algorithm by 90% by just changing one line of code. It took me half an hour to find that line of code, and I would never have even guessed that it was this line without running the algorithm through a profiler.
Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 4659
    
    5

Originally posted by Ilja Preuss:
It took me half an hour to find that line of code, and I would never have even guessed that it was this line without running the algorithm through a profiler.


Notice I didn't claim that I could improve proformance by 50% in a few minutes. :-) Sometimes it takes a long time, but you can always do it. Sometimes you have to replace the algorithms or data structures, or even not call the database.

Speaking of databases, not calling a database is the most reliable way to improve performance. Much faster than optimizing 1000 lines of code.
 
Don't get me started about those stupid light bulbs.
 
subject: Performance Impact String vs StringBuilder