Skip to content

Commit b1950c2

Browse files
committed
Optimize regular expressions for identifying code types
By only matching one regex with a little bit more complexity and differentiating the results by a capture group the performance of checking for matches gets way better. Because this regex has to be matched for each line it is compiled only once to save this overhead for most matches.
1 parent bba72cb commit b1950c2

1 file changed

Lines changed: 18 additions & 14 deletions

File tree

  • src/main/java/org/variantsync/diffdetective/diff/difftree

src/main/java/org/variantsync/diffdetective/diff/difftree/CodeType.java

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package org.variantsync.diffdetective.diff.difftree;
22

3+
import java.util.regex.Matcher;
4+
import java.util.regex.Pattern;
5+
36
public enum CodeType {
47
IF("if"),
58
ENDIF("endif"),
@@ -20,23 +23,24 @@ public boolean isMacro() {
2023
return this != ROOT && this != CODE;
2124
}
2225

23-
final static String ifRegex = "^[+-]?\\s*#\\s*if.*$";
24-
final static String endifRegex = "^[+-]?\\s*#\\s*endif.*$";
25-
final static String elseRegex = "^[+-]?\\s*#\\s*else.*$";
26-
final static String elifRegex = "^[+-]?\\s*#\\s*elif.*$";
26+
final static Pattern regex = Pattern.compile("^[+-]?\\s*#\\s*(if|endif|else|elif)");
2727

2828
public static CodeType ofDiffLine(String line) {
29-
if (line.matches(ifRegex)) {
30-
return IF;
31-
} else if (line.matches(endifRegex)) {
32-
return ENDIF;
33-
} else if (line.matches(elseRegex)) {
34-
return ELSE;
35-
} else if (line.matches(elifRegex)) {
36-
return ELIF;
37-
} else {
38-
return CODE;
29+
Matcher matcher = regex.matcher(line);
30+
if (matcher.find()) {
31+
String id = matcher.group(1);
32+
if (id.equals(IF.name)) {
33+
return IF;
34+
} else if (id.equals(ENDIF.name)) {
35+
return ENDIF;
36+
} else if (id.equals(ELSE.name)) {
37+
return ELSE;
38+
} else if (id.equals(ELIF.name)) {
39+
return ELIF;
40+
}
3941
}
42+
43+
return CODE;
4044
}
4145

4246
public static CodeType fromName(final String name) {

0 commit comments

Comments
 (0)