string.replaceAll() 性能是否受到字符串不变性的影响? [英] Does string.replaceAll() performance suffer from string immutability?

查看:56
本文介绍了string.replaceAll() 性能是否受到字符串不变性的影响?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在替换 1,000 个匹配实例的大字符串上调用了 replaceAll().这是否意味着由于字符串不变性而在进程中创建和重新分配了 1,000 个字符串?有没有更快的替代方案?

Lets say I called replaceAll() on a big string that replaced 1,000 matching instances. Does it mean that 1,000 strings were created and reassigned in process because of string immutability? Is there any faster alternatives?

推荐答案

如果你深入研究 String,您会看到它将 replaceAll() 委托给 模式 &Matcher Matcher.replaceAll() 使用 StringBuilder 来存储最终返回的值.

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() 不会创建多于少量的对象.

So no, String.replaceAll() does not create more than a small number of objects.

这篇关于string.replaceAll() 性能是否受到字符串不变性的影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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