| versions | 0095+ |
|---|
| contributors | tomc |
| started on | 2006-01-30 06:32 |
The String class provided by the Java standard libraries is invaluable, but before using it, there are a few things you should be aware of.
this article needs expanding :)
Put briefly, if you want to compare two Strings you should always use
if (name.equals(BEST_NAME)) {}
and never
if (name == BEST_NAME) {}
because the latter just checks whether they are the same String object, which can be false even if two objects contain the same text.
More information in the following threads:
http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1100632237;start=4
http://processing.org/discourse/yabb/YaBB.cgi?board=Syntax;action=display;num=1094688897;start=2
One of the properties of a Java String is that it is immutable. This means that once it's been created with some text, that text can never be changed without making a new String. So when you do something like this:
String sentence = "Hello, "; sentence += name + "!";
The original object containing “Hello, ” is thrown away and an entirely new String object is created instead. If you're doing a lot of appending, creating all these new String objects can get really slow.
StringBuffer was designed specifically for doing lots of appending. Its append() method is fast, and when you want the final result you can simply use toString().
StringBuffer sb = new StringBuffer("Hello, "); sb.append(name); sb.append("!"); String myFinalString = sb.toString();
(For more advanced users: if you know StringBuffer will only be modified in one thread (quite likely for the vast majority of Processing apps) then you can swap it out for StringBuilder, which is even faster.)
Please list any links you think are essential reading related to this hack:
Messing with the String store using Reflection - anything in this article is not recommended!