This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
No. Or rather, the question is wrong. Methods don't return Strings, or any other objects. Methods return references.
You can't tell from looking at a method whether the reference it returns is a reference to a newly created object or a reference to an object which it just created specifically for the purpose. But at any rate the example you give is almost certainly an unnecessary micro-optimization at best.
But didn't we just have a discussion about premature optimization in another thread? It isn't worth making a change which will save a microsecond unless you're going to be executing that code a million times in rapid succession. Please read the Wikipedia article about Program optimization, in particular the section about premature optimization. You should really concentrate your efforts elsewhere.
As is so often the case, the answer is "it depends". Some methods will create new objects, and others won't. For example, HttpServletRequest..getParameter() doesn't; all the parameters are held in a Map inside the request, and getParameter just returns objects that already existed. On the other hand, a method like String.substring() pretty much always returns a new object, as that's what it's designed to do. There are even going to be methods that return new objects only some of the time.
Often, combining common expressions the way you have done here is a good idea even if it really doesn't save any memory or time, because it makes your code easier to read.
Here's another thing to pay attention to: your original example assumes that
will return the same value from both calls in the original snippet. In many cases that's a reasonable assumption but there are cases where calling a method twice will return two different values. In those cases you would have to respect the design of the method and call it as many times as necessary.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: do methods that return String create them on the heap?