[英]Why use char[] instead of String?
In Thread.java , line 146, I have noticed that the author used a char[]
instead of a String
for the name field. 在第146行的Thread.java中 ,我注意到作者使用了
char[]
而不是String
字段。 Are there any performance reasons that I am not aware of? 有没有我不知道的性能原因?
getName()
also wraps the character in a String before returning the name. getName()
还在返回名称之前将字符包装在String中。 Isn't it better to just use a String
? 使用
String
不是更好吗?
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. 我怀疑
char[]
是出于性能原因而在Thread
中使用,早在Java中的这些东西需要尽一切努力才能获得不错的性能时。 With the advent of modern JVMs, such micro-optimizations have long since become unimportant, but it's just been left that way. 随着现代JVM的出现,这种微优化早已变得不重要,但它只是一直保持这种状态。
There's a lot of weird code in the old Java 1.0-era source, I wouldn't pay too much attention to it. 在旧的Java 1.0时代源代码中有很多奇怪的代码,我不会过分关注它。
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. 也许他们考虑了一些优化,也许编写这段代码的人只是更习惯于字符串的C风格
char*
数组,或者可能在编写代码时他们不确定字符串是否是不可变的。 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. 但是使用这段代码,
Thread.getName()
调用Thread.getName()
,都会创建一个新的char数组,因此这个代码实际上比使用字符串更重。
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.
如果你这样做,你也可以使用char数组来加快复制速度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.