在常量池中操作字符串与在非常量池中操作字符串-性能 [英] Manipulation of a string in constant pool vs Manipulation of a string in non-constant pool - Perfomance

查看:118
本文介绍了在常量池中操作字符串与在非常量池中操作字符串-性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更改一个类似

if("T".equalsIgnoreCase(bo.getSubjectType()))  //method-1

if(String.valueOf('T').equalsIgnoreCase(bo.getSubjectType()))  //method-2

因此,我写了一个示例代码

So for that reason I wrote a sample code

String s1 = "T";
String s2 = "T";
char c1 = 'T';
char c2 = 'T';
System.out.println(String.valueOf(c1) == String.valueOf(c2));   //  false
System.out.println(s1 == s2);   //  true

几乎说String.valueOf(arg)产生一个字符串文字并将其放在constant pool中.所以我的问题是,当我们尝试在non-constant池中和在constant pool池中操作String时,性能上是否会有任何对比-基本上哪种方法更好地使用 method-1 方法2 ?

Which pretty much says String.valueOf(arg) produces a String literal and places it in constant pool. So my question is whether there would be any contrast in performance when we try to manipulate a String in non-constant pool and that in a constant pool - basically which one would be better approach method-1 or method-2?

推荐答案

if(String.valueOf('T').equalsIgnoreCase(bo.getSubjectType()))

像这样编写它没有任何优势.

There is no advantage whatsoever to writing it like this.

String.valueOf('T')将始终返回一个新字符串,该字符串等于"T",因为String.valueOf(char)的结果(或任何valueOf重载)不会被缓存.没有理由一遍又一遍地创建相同的字符串.

String.valueOf('T') will always return a new string, equal to "T", because the result of String.valueOf(char) (or any valueOf overload, for that matter) is not cached. There is no reason to keep on creating the same string over and over.

另外,它更冗长.

只需坚持使用方法1.

这篇关于在常量池中操作字符串与在非常量池中操作字符串-性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆