+5  A: 
String foo = "some string literal";

Is certainly the fastest way to make a String. It's embedded in the .class file and is a simple memory look-up to retrieve.

Using String.format when you have nothing to really format just looks ugly and might cause junior developers to cry.

If the String is going to be modified, then StringBuilder is the best since Strings are immutable.

Ben S
Using String.format when you have nothing to really format would probably also cause senior developers to cry, too.
JasCav
+18  A: 

If there is only one string then:

String foo = "123456";

Is fastest. You'll notice that the String.format line has "%s%" declared in it, so I don't see how the lecturer could possibly think that was faster. Plus you've got a method call on top of it.

However, if you're building a string over time, such as in a for-loop, then you'll want to use a StringBuilder. If you were to just use += then you're building a brand new string every time the += line is called. StringBuilder is much faster since it holds a buffer and appends to that every time you call append.

jasonh
my thoughts exactly.
pstanton
Yeah, if you're declaring a string literal, then just embedding it is obviously the fastest way. I had a programming language prof once tell the class that Java didn't have pointers, so you couldn't create things like linked lists, he thought all the java collections were implemented in C or something. I had another lecturer say that 'secure' websites were ones that ended in '.shtml' (rather then starting with https) Sometimes they just don't know what they're talking about
Chad Okere
Plus in a tight loop you could be creating a HUGE number of strings each one a little bigger than the last.This is true in C# (well .Net) as well.I also agree with the comment from Eric Wendelin that you should write a test to see. Don't tell your prof the opinions of people on teh interwebz when you could show him documented proof of whether he is right or wrong. I would do a number of test cases: speed to create one string via each method, speed to create lots in a loop, etc.
jeffa00
+1 for the explanation as to why StringBuilder is faster.
JasCav
@jeffa00: I agree, instrumented testing is the best way to prove this. However, beware as professors (in my experience anyway) don't like to be challenged. *Especially* don't do it in class.
jasonh
If you have many occurrences of "123456" then they all refer to the same intern()-ed value. But if you run String.format() on multiple "123456" you generate duplicate copies.
Jim Ferrans
+2  A: 

If your string is known at compile-time, then using a literal is best: String foo = "123456";.

If your string is not known at compile-time and is composed of an aggregation of smaller strings, StringBuilder is usually the way to go (but beware thread-safety!).

Using String foo = String.format("%s", 123456); could reduce your .class' size and make class-loading it a tiny bit faster, but that would be extremely aggressive (extreme) memory tuning there ^^.

Romain
+2  A: 

In your second example, using:

String foo = String.format("%s", 123456);

doesn't buy you anything; 123456 is already a constant value, so why not just assign foo = "123456"? For constant strings, there's no better way.

If you're creating a string from multiple parts being appended together at runtime, use StringBuffer or StringBuilder (the former being thread-safe).

mpobrien
+1  A: 

As has been pointed out, if you're just building a single string with no concatenation, just use String.

For concatenating multiple bits into one big string, StringBuffer is slower than StringBuilder, but StringBuffer is synchronized. If you don't need synchronization, StringBuilder.

Dean J
+3  A: 

This whole discussion is moot. Please read this article by Jeff, i.e., the guy who created Stack Overflow.

The Sad Tragedy of Micro-Optimization Theater

Please refer your instructor to this post and ask him to stop ruining his/her student's brains with useless information. Algorithmic optimizations are where your code will live or die, not with what method you use to construct strings. In any case, StringBuilder, and String formatter have to execute ACTUAL CODE with REAL MEMORY, if you just construct a string it gets set aside during compile time and is ready to be used when you need it, in essence, it has 0 run-time cost, while the other options have real cost, since code actually needs to be executed.

Michael
Not to get too picky, but I think you mean to say that the discussion is "moot". Although it is "mute" too since SO doesn't have sounds... ;)
jasonh
Let's micro-optimize this post! :)
Tim
Thanks for the spelling mistake correction.
Michael
If the OP had a too-slow program and tried to optimize it by looking at trivial string concatenations, I might have agreed with you, but this is a question where the OP wonders how something works. Saying "don't optimize until you need it" to someone who is trying to learn about their programming platform is like saying "don't bother buying an insurance until your house is on fire". (As for the rest of your post, I agree fully.)
gustafc
A: 

The first example you gave is the fastest and the simplest. Use that.

Each piece of code you added in those examples makes it significantly slower and more difficult to read.

I would suggest example 2 is at least 10-100x slower than example 1 and example 3 is about 2x slower than example 2.

Did your processor provide any justification for this assertion?

BTW: Your first example doesn't construct a String at all (which is why it is fastest), it just hands you a String sitting in the String constant pool.

Peter Lawrey
+1  A: 

Are you 100% certain that the instructor was not talking about something like:

String foo = "" + 123456;

I see my students do that type of thing "all the time" (a handful will do that each term). The reason that they do it is that some book showed them how to do it that way. Shakes head and fist at lazy book writers!

TofuBeer
+2  A: 

Slightly off-topic, but I wish that the whole "must-not-use-plus-to-concatenate-strings-in-Java" myth would go away. While it might have been true in early versions of Java that StringBuffer was faster and "+ was evil", it is certainly not true in modern JVMs that are taking care of a lot of optimisations.

For example, which is faster?

String s = "abc" + "def";

or

    StringBuffer buf = new StringBuffer();
 buf.append("abc");
 buf.append("def");
 String s = buf.toString();

The answer is the former. The JVM recognises that this is a string constant and will actually put "abcdef" in the string pool, whereas the "optimised stringbuffer" version will cause an extra StringBuffer object to be built.

Another JVM optimisation is

String s = onestring + " concat " + anotherstring;

Where the JVM will work out what the best way of concatenating will be. In JDK 5, this means a StringBuilder will be internally used and it will be faster than using a string buffer.

But as other answers have said, the "123456" constant in your question is certainly the fastest way and your lecturer should go back to being a student :-)

And yes, I've been sad enough to verify this by looking at the Java bytecode...

beny23