9

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?

1
  • 3
    Calls 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. Commented Nov 21, 2011 at 5:21

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I suspected this too. But then I saw String name in ThreadGorup I was confused. Thanks for the answer.
I am going to accept this answer because as many people suggested there was no really a good reason.
String is immutable so thats why he used it. Effective java 2end edition says that "Always use String alternative where ever possible" by Josha Blouch
2

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.

Comments

1

Maybe the reason was security protection? String can be changed with reflection, so the author wants copy on read and write. If you are doing that, you might as well use char array for faster copying.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.