0

Whenever I tried to generated toString() method with IntelliJ IDEA, I see

return ... +
        ", some='" + '\'' + // some is an String field
        '}';

Does it make any significant performance gain against following signature?

return ... +
        ", some='" + "'" +
        "}";

Or is it just a template and means nothing?

Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
  • The `char` type is obsolete, unable to represent even half of the over 140,000 characters defined in Unicode. Instead use Unicode code point integer numbers. – Basil Bourque Jul 19 '20 at 04:34
  • 1
    Code point numbers can't represent everything in unicode that a user would consider a character either. it's not really relavent here though.... – plugwash Jul 19 '20 at 04:48

1 Answers1

3

There is possibly a small performance difference in concatenating a char versus a String.

  • In the char case, the concatenation will most likely just be an append of a char to a StringBuilder.

  • In the String case, a naive implementation would entail a loop to copy all of the characters in the String. Also, there is an extra level of indirection, possibly two null check, and a possible array bounds check when accessing the string's character (or byte) array.

HOWEVER

  1. While the performance difference (if you measured it) may be significant in a micro-benchmark for that toString() method, it is typically going to be insignificant in the context of a real applications.

    In general, it is not worthwhile use of a programmer's time to focus on performance at this level of detail. The significant performance issues are likely to be in other areas. A good strategy is to use a benchmark, profile, optimize methodology ... once you have a code that is feature complete and passing tests.

  2. There are plans to introduce JIT "smarts" to optimize String concatenation sequences; see https://openjdk.java.net/jeps/280.

    I am not sure if this particular case is optimized (yet) in the latest Java JIT compilers. But it is clearly on the cards that the optimization will be added.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216