java - 使用 Pattern/Matcher 是否比循环遍历字符串并查找字符更有效?

标签 java regex performance iteration

我正在开发一个项目,该项目将通过 java 文件查找特定方法,并将该方法占用的行输出到文件中。我已经在使用 Pattern 和 Matcher 来查找方法,但随后我遍历一行中的字符以查找匹配的大括号。

我的问题是,使用另一个模式/匹配器来查找花括号对会更有效吗?

这里是查找行范围的方法,如果有帮助的话:

        String line;
        int currentLineNumber = 0;

        int methodStart = 0;
        int methodEnd = 0;

        int braceCount = 0;

        Matcher matcher;

        while ((line = lineReader.readLine()) != null) { // Must set line's value here because readLine() increments line number

            currentLineNumber = lineReader.getLineNumber();
            matcher = p.matcher(line); // initialize matcher with Pattern

            if (matcher.find()) { // if the line has a regex hit, store the line number as currentLine
                methodStart = currentLineNumber;
            }

            if (currentLineNumber >= methodStart && methodStart != 0) { // make sure that we've found the method
                for (int i = 0; i < line.length(); i++) { // iterates through characters in the line
                    /*
                     * Start with a braceCount of 0. When you find a starting brace, increment.
                     * When you find an ending brace, decrement. When braceCount reaches 0 again,
                     * you will know that you have reached the end of the method.
                     * 
                     * Could possibly reduce complexity/increase efficiency by using set of patterns/matchers
                     * to find braces. 
                     */
                    if (line.charAt(i) == '{') 
                        braceCount++;

                    if (line.charAt(i) == '}') {
                        braceCount--;
                        if (braceCount == 0) {
                            methodEnd = currentLineNumber;
                            return new int[] { methodStart, methodEnd };
                        }
                    }

                }

            }

        }

最佳答案

在您的特定情况下可能不是。

您按顺序扫描 Java String 一次。这比构建一个 Matcher 然后使用它来做同样的事情要快。 Matcher 也必须至少扫描一次 String,这里面没有魔法。

在任何情况下,在进行与性能相关的优化之前,始终使用分析器(例如 VisualVM)。


一个可能更大的问题是首先使用正则表达式解析 Java。这样的解决方案不可避免地是脆弱的(例如,可以在一行中写一个Java方法,可以有嵌套类,泛型等)。

有很多Java parsers围绕它可以以更强大的方式完成工作。

关于java - 使用 Pattern/Matcher 是否比循环遍历字符串并查找字符更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149855/

相关文章:

没有 JIT 的 Android 设备

javascript - 快速检查大文件是否存在 javascript

algorithm - 用于在类别的二维网格中搜索坐标的最佳数据结构

java - 将 RecyclerView 的 getItemCount() 与 onCreateViewHolder 同步

java - 接口(interface)定义和泛型。这应该有不同的定义吗?

套接字上下文中的 Java 和二进制数据

php - 字符串的特殊 preg_match

java - 使用 Java 中的多态性替换 If/Else

jquery - 寻找jquery正则表达式模式来匹配0-24,允许小数

jquery - 正则表达式和 jQuery : lower case