Apache StringUtils 与 Replace() 的 Java 实现
What would be the difference between Java 1.4.2's implementation of replace, and Apache 2.3's implementation? Is there a performance gain one over another?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您链接到的
String.replace()
方法采用两个char
值,因此它只会用另一个字符替换一个字符(尽管可能多次)。另一方面,
StringUtils.replace()
方法将String
值作为搜索字符串和替换值,因此它可以替换较长的子字符串。Java 中的类似方法为
replaceAll()
。replaceAll()
可能比StringUtils
方法慢,因为它支持正则表达式,因此引入了首先编译搜索字符串并运行正则表达式搜索的开销。请注意,Java 5 引入了
String.replace(CharSequence, CharSequence)
其作用与StringUtils.replace(String,String)
(除非它的任何参数为null
,否则会抛出NullPointerException
)。请注意,CharSequence 是由 String 实现的接口,因此您可以在此处使用普通的旧 String 对象。The
String.replace()
method you linked to takes twochar
values, so it only ever replaces on character with another (possibly multiple times, 'though).The
StringUtils.replace()
method on the other hand takesString
values as the search string and replacement, so it can replace longer substrings.The comparable method in Java would be
replaceAll()
.replaceAll()
is likely to be slower than theStringUtils
method, because it supports regular expressions and thus introduces the overhead of compiling the search string first and running a regex search.Note that Java 5 introduced
String.replace(CharSequence, CharSequence)
which does the same thing asStringUtils.replace(String,String)
(except that it throws aNullPointerException
if any of its arguments arenull
). Note thatCharSequence
is an interface implemented byString
, so you can use plain oldString
objects here.时间几乎相同!
我编辑了代码以删除
replace2
的开销,这不是由于 JDK 实现造成的。Times are almost the same!
I've edited the code to drop out overheads of
replace2
which were not because of JDK implementation.1.4.2 替换了仅使用
char
参数进行的操作,而 Apache 2.3 则接受字符串。1.4.2 replaces operates only with
char
arguments whereas the Apache 2.3 one takes in strings.String.replace(char, char)
无法替换整个字符串,StringUtils.replace(..)
获取null
值。如果第一个字符串不为空,
String.replace(CharSequence s1, CharSequence s2)
将执行相同的操作。否则它会抛出一个NullPointerException
String.replace(char, char)
can't replace whole stringsnull
values withStringUtils.replace(..)
.String.replace(CharSequence s1, CharSequence s2)
will do the same thing if the first string is not-null. Otherwise it will throw aNullPointerException
如果我没记错的话,Apache 的速度要快得多。受到推崇的。
Apache's is quite a bit faster, if I recall correctly. Recommended.
要使用 StringUtil.Replace 将字符串字符替换为另一个字符串,我尝试了以下操作,并且它可以很好地从单个字符串替换多个字符串值。
这将用新提供的值替换 info 的字符串值...
To replace a string character with another string using
StringUtil.Replace
, I tried following and it's working fine for me to replace multiple string values from a single string.This will replace the String value of info with newly provided value...