String replaceAll()与Matcher replaceAll()(性能差异) [英] String replaceAll() vs. Matcher replaceAll() (Performance differences)

查看:476
本文介绍了String replaceAll()与Matcher replaceAll()(性能差异)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

非常简单的问题,但这是来自一个C / C ++人进入Java的复杂性。

Pretty simple question, but this is coming from a C/C++ person getting into the intricacies of Java.

我知道我可以启动jUnit和一些性能我自己的测试得到答案;但我只是想知道它是否在那里。

I understand I can fire up jUnit and a few performance tests of my own to get an answer; but I'm just wondering if this is out there.

String.replaceAll()和Matcher.replaceAll()之间是否存在已知的差异(在匹配器上)在性能方面从Regex.Pattern创建的对象?

Are there known difference(s) between String.replaceAll() and Matcher.replaceAll() (On a Matcher Object created from a Regex.Pattern) in terms of performance?

此外,两者之间的高级API是什么区别? (不变性,处理NULL,处理空字符串,制作咖啡等。)

Also, what are the high-level API 'ish differences between the both? (Immutability, Handling NULLs, Handling empty strings, making coffee etc.)

推荐答案

根据 String.replaceAll ,它有关于调用方法的以下内容:

According to the documentation for String.replaceAll, it has the following to say about calling the method:



形式的这种方法的调用 str.replaceAll(regex,repl)
产生与
完全相同的结果表达式

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)


因此,可以预期调用 String.replaceAll之间的性能,并明确创建 Matcher 模式 应该是相同的。

Therefore, it can be expected the performance between invoking the String.replaceAll, and explicitly creating a Matcher and Pattern should be the same.

编辑

正如评论中指出的那样,性能差异不存在将是真实的从字符串匹配单次调用 replaceAll ,但是,如果需要对 replaceAll 执行多次调用,可以预期保持已编译的模式,因此不必每次都执行相对昂贵的正则表达式模式编译。

As has been pointed out in the comments, the performance difference being non-existent would be true for a single call to replaceAll from String or Matcher, however, if one needs to perform multiple calls to replaceAll, one would expect it to be beneficial to hold onto a compiled Pattern, so the relatively expensive regular expression pattern compilation does not have to be performed every time.

这篇关于String replaceAll()与Matcher replaceAll()(性能差异)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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