In Thread.java, line 146, I have noticed that the author used a char[] instead of a String for the name field. Are there any performance reasons that I am not aware of? getName() also wraps the character in a String before returning the name. Isn't it better to just use a String?
-
3Calls to String.{ getChars, getBytes, toLowerCase, ... } all return new objects which are copies of the original string. If your working with large strings or calling one of these methods many times. You may end up with unnecessary additional garbage collections. For Example, imagine an HTTP heartbeat that for whatever reason called OutputStream.write( epochTimeString.getBytes() ) on every beat. You have to worry about these details more often if you do work with Mobile JVMs.eSniff– eSniff2011-11-21 05:21:08 +00:00Commented Nov 21, 2011 at 5:21
3 Answers
In general, yes. I suspect char[] was used in Thread for performance reasons, back in the days when such things in Java required every effort to get decent performance. With the advent of modern JVMs, such micro-optimizations have long since become unimportant, but it's just been left that way.
There's a lot of weird code in the old Java 1.0-era source, I wouldn't pay too much attention to it.
3 Comments
String name in ThreadGorup I was confused. Thanks for the answer.Hard to say. Perhaps they had some optimizations in mind, perhaps the person who wrote this code was simply more used to the C-style char* arrays for strings, or perhaps by the time this code was written they were not sure if strings will be immutable or not. But with this code, any time a Thread.getName() is called, a new char array is created, so this code is actually heavier on the GC than just using a string.