简体   繁体   English

string.replaceAll()性能是否受到字符串不变性的影响?

[英]Does string.replaceAll() performance suffer from string immutability?

Lets say I called replaceAll() on a big string that replaced 1,000 matching instances. 假设我在一个替换1,000个匹配实例的大字符串上调用了replaceAll()。 Does it mean that 1,000 strings were created and reassigned in process because of string immutability? 这是否意味着由于字符串不变性而创建并重新分配了1,000个字符串? Is there any faster alternatives? 还有更快的选择吗?

If you dig into String , you'll see that it delegates replaceAll() to Pattern & Matcher and Matcher.replaceAll() uses a StringBuilder to store the eventually returned value. 如果你深入研究String ,你会看到它将replaceAll()委托给PatternMatcher, Matcher.replaceAll()使用StringBuilder来存储最终返回的值。

So no, String.replaceAll() does not create more than a small number of objects. 所以不,String.replaceAll()不会创建多个对象。

you can try with a StringBuffer / StringBuilder , since they are mutable CharSequence s: 你可以尝试使用StringBuffer / StringBuilder ,因为它们是可变的 CharSequence s:

CharSequence veryBigString = new StringBuilder();
Pattern.compile(regex).matcher(veryBigString).replaceAll(replacement);

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

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