洛克的猜想

Roco's conjecture

Sometimes just a few lines of code may affect performance much.

The following tips are just from my experience. You may already know this :)

1. Implement a log wrapper to log big Object ( assuming that big Object will cost much time to call toString() )

log wrapper like this.
void log.debug(Object o, Object bigObject) {

if (DEBUG >= currentLogLevel) {
log.debug(o + bigObject);
}
}
Comparing to traditional log.debug(o + bigObject), this wrapper will only call bigObject.toString() when log level is lower than DEBUG, saving a lot of time from computing useless toString().


2. Use StringBuffer instead of StringBuilder when constructing new String from Strings.
StringBuilder is known in style like this: Clazz.print("a" + "b" + "c").
Every time, a "+" operation will generate a new String, this will cost more time and space. (String is not mutable)
StringBuffer is known is style like this:
StringBuffer buf = new StringBuffer();
buf.append("a");
buf.append("b");
buf.append("b");
For every method, it will modify the existing object. (StringBuffer is mutable)


3. Use String.indexOf before String.replace
The same reason as before. String.replace will build a new String, to save time and space, we'd better use indexOf to check whether this string has the str to be replaced.
This will gain much more when most time the String.indexOf return -1 (means there is little probability need to call replace).


4. Use ArrayList instead of Vector.
Although Vector is thread-safe, but it will also bring a lot of performance overhead. So usually ArrayList should be better to use instead of Vector, especially when the data is owned internally by single thread.