String replaceAll()与Matcher replaceAll()(性能差异)

编程入门 行业动态 更新时间:2024-10-25 03:33:00
本文介绍了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 Patternpile(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()(性能差异)

本文发布于:2023-10-16 05:59:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1496694.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:差异   性能   String   replaceAll   Matcher

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!