Skip to content

Commit

Permalink
[#2091] Improve memory usage by refactoring Regex compilation (#2092)
Browse files Browse the repository at this point in the history
Improve memory usage by refactoring Regex compilation

Currently, Regex checking is used in conjunction with iteration. This
pattern of coding is frowned upon due to the excessive Regex pattern
compilation, causing the program to run slower and consume more
memory.

By moving the Regex pattern compilation outside of the iteration, and
by using `Matcher` objects to check if the strings match the Regex
performance, we can potentially remove this performance bottleneck.

Let's move to refactor the code and remove such instances of Regex use
in iterative loops.
  • Loading branch information
georgetayqy authored Jan 26, 2024
1 parent c2ac8d1 commit 54ba5ec
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
9 changes: 7 additions & 2 deletions src/main/java/reposense/model/Author.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.nio.file.PathMatcher;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
* Represents a Git Author.
Expand Down Expand Up @@ -74,8 +75,10 @@ public Author(Author another) {
* @throws IllegalArgumentException if any of the values do not meet the criteria.
*/
private static void validateEmails(List<String> emails) throws IllegalArgumentException {
Pattern emailPattern = Pattern.compile(COMMON_EMAIL_REGEX);

for (String email : emails) {
if (!email.matches(COMMON_EMAIL_REGEX)) {
if (!emailPattern.matcher(email).matches()) {
throw new IllegalArgumentException(String.format(MESSAGE_UNCOMMON_EMAIL_PATTERN, email));
}
}
Expand All @@ -87,8 +90,10 @@ private static void validateEmails(List<String> emails) throws IllegalArgumentEx
* @throws IllegalArgumentException if any of the values do not meet the criteria.
*/
private static void validateIgnoreGlobs(List<String> ignoreGlobList) throws IllegalArgumentException {
Pattern globPattern = Pattern.compile(COMMON_GLOB_REGEX);

for (String glob : ignoreGlobList) {
if (!glob.matches(COMMON_GLOB_REGEX)) {
if (!globPattern.matcher(glob).matches()) {
throw new IllegalArgumentException(String.format(MESSAGE_UNCOMMON_GLOB_PATTERN, glob));
}
}
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/reposense/util/StringsUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ public class StringsUtil {
public static String filterText(String text, String regex) {
String[] split = text.split("\n");
StringBuilder sb = new StringBuilder();
Pattern regexPattern = Pattern.compile(regex);

for (String line: split) {
if (line.matches(regex)) {
sb.append(line + "\n");
if (regexPattern.matcher(line).matches()) {
sb.append(line).append("\n");
}
}

Expand Down

0 comments on commit 54ba5ec

Please sign in to comment.