String performance optimization in Java

  • 2020-04-01 03:48:11
  • OfStack

Instead of using a String constructor, use a String if possible.

Two special cases:

1) want to convert char [] to a String,
2) use the substring() method of a large String object;

String.equals() is faster than string.equalsignorecase ();

Try to use StringBuilder to construct a String instead of the "+" operator and string.concat () (unless it's an expression, String s = a + b + c);

StringBuilder is not synchronized, so it is faster than StringBuffer.

Add a capacity parameter to the String[Buffer|Builder] constructor because creating a Buffer that is too small can degrade performance.

String.length()==0 is faster than string.equals (""). With Java 6, string.isempty () is faster;

Calling string.tostring () is meaningless;

Since String is immutable, all String methods that return modified strings return a new instance;

String.split(regex) actually simply calls the Pattern.compile(regex).split(this, limit), and each compile() returns a new Pattern. So if you call split frequently, it's best to create a single Pattern instance and reuse it instead of a split().

The above is the article to share with you, I hope you can enjoy.

Please take a moment to share the article with your friends or leave a comment. We sincerely appreciate your support!


Related articles: