简体   繁体   English

Java - 使用 new String() 或 valueOf(char[])

[英]Java - use new String( ) or valueOf(char[])

I am upgrading an application from Java 8 to Java 9. Work was started several years ago by someone no longer with the company.我正在将应用程序从 Java 8 升级到 Java 9。工作是几年前由不再在公司工作的人开始的。

They replaced uses of new Integer(int) with Integer.valueOf() I understand this has advantages in terms of avoiding unnecessary object, and have read several posts on the subject including Joshua Bloch on Considering static factory methods instead of constructors他们用Integer.valueOf()替换了new Integer(int)使用我知道这在避免不必要的对象方面具有优势,并且已经阅读了有关该主题的几篇文章,包括Joshua Bloch 关于考虑静态工厂方法而不是构造函数的文章

is there any value to replacing code like val x = new String("A" + "\ê" + "\ñ" + "\ü" + "C") with是否有任何价值来替换像val x = new String("A" + "\ê" + "\ñ" + "\ü" + "C")的代码

String.valueOf(new char[] { 'A' , '\u00ea' , '\u00f1' , '\u00fc' , 'C' })

similarly how, if at all would you update同样如何,如果你会更新

new String[]{"alpha", "beta", "plabelColor"};

Don't introduce micro optimisations, if you cannot measure the impact AND require the optimisation.如果您无法衡量影响并需要优化,请不要引入微优化。

We are talking about tiny micro optimisations here.我们在这里谈论的是微小的微优化。 If your application is not a high frequency trading application, where every nano second matters, you should favour readability of the code over micro optimisations.如果您的应用程序不是高频交易应用程序,其中每一纳秒都很重要,那么您应该更喜欢代码的可读性而不是微优化。 These optimisations might even result in the same code after compiling (or realeasing a newer compiler optimisation).这些优化甚至可能会在编译(或重新发布更新的编译器优化)后产生相同的代码。 These kind of optimisations hardly have any influence on your users measurable response time.这些优化几乎不会对您的用户可测量的响应时间产生任何影响。

If you want to measure the impact, I suggest you use JMH for it.如果你想衡量影响,我建议你使用JMH

Replacing new Integer(int) with Integer.valueOf(int) is (more than just) a good idea - new Integer(int) has been deprecated (Java 9) and marked for removal (Java 16).Integer.valueOf(int)替换new Integer(int)是(不仅仅是)一个好主意 - new Integer(int)已被弃用(Java 9)并标记为删除(Java 16)。

val x = new String("A" + "\ê" + "\ñ" + "\ü" + "C") is not really Java; val x = new String("A" + "\ê" + "\ñ" + "\ü" + "C")不是真正的 Java; if Java, I would recommend var x = "A" + "\ê" + "\ñ" + "\ü" + "C" or even var x = "A\ê\ñ\üC" (unless a new, not-interned String is required (no idea why))如果是 Java,我会推荐var x = "A" + "\ê" + "\ñ" + "\ü" + "C"甚至var x = "A\ê\ñ\üC" (除非新的,非实习字符串是必需的(不知道为什么))

new String[]{"alpha", "beta", "plabelColor"} - no update needed new String[]{"alpha", "beta", "plabelColor"} - 不需要更新

There seems to be no reason to replace new String(char[]) with String.valueOf(char[]) , and in fact the latter is likely implemented by just doing the former - here's the source code of the String class from JDK 9, for example ( link ):似乎没有理由用String.valueOf(char[])替换new String(char[]) ,实际上后者很可能是通过执行前者来实现的 - 这是 JDK 9 中String类的源代码,例如( 链接):

    public static String valueOf(char data[]) {
        return new String(data);
    }

So the only difference would be one extra method call (which at best would be inlined by the JIT).所以唯一的区别是一个额外的方法调用(最多由 JIT 内联)。 On the other hand, if there is a difference then it would be extremely small, and not worth considering, so instead of thinking about performance you should probably choose based on which way you think is more readable.另一方面,如果存在差异,那么它将非常小,不值得考虑,因此与其考虑性能,您还应该根据您认为更具可读性的方式进行选择。

That said, the code in your example is not using the new String(char[]) constructor, it is using the new String(String) constructor to copy a string.也就是说,您示例中的代码没有使用new String(char[])构造函数,而是使用new String(String)构造函数来复制字符串。 This is not needed, you can just write the expression which creates the string without calling the constructor, unless there is some reason your code requires the string object to not be interned (and if it does, that smells like a bad design to me.)这不是必需的,您可以只编写创建字符串的表达式而不调用构造函数,除非您的代码出于某种原因要求不实习字符串对象(如果确实如此,这对我来说就像一个糟糕的设计。 )


If you do think there might be some benefit in caching frequently-used strings, you should implement a cache yourself, design it to be optimised for the kind of strings your application is likely to be dealing with, and then benchmark it to see if it's actually faster.如果您确实认为缓存常用字符串可能有一些好处,那么您应该自己实现缓存,将其设计为针对您的应用程序可能要处理的字符串类型进行优化,然后对其进行基准测试以查看它是否实际上更快。 You'll have the cost of checking the cache every time, and this cost will likely be larger for strings than for integers, especially if it involves hashing and testing equality of strings;你必须每次检查缓存的成本,这个成本很可能会为字符串比整数更大,特别是当它涉及到字符串的散列和测试平等; so if there are too many cache misses then the net effect would be negative.因此,如果缓存未命中太多,那么净效应将是负面的。 The cache miss rate will be highly dependent on your application, so you do want to benchmark with realistic data.缓存未命中率将高度依赖于您的应用程序,因此您确实希望使用真实数据进行基准测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM