'Enclose code in anonymous brackets saves memory?
I'm a beginner and for some reason, I like to make effort to save memory. For now I think it's fun.
So in this problem, I have a regex that matches kebab-case words and later turns them into camel-case words, and I want to know if that is some occurrence in a given string. I tried Matcher.matches() but I found out that it only works if the entire string is matched, so I only could think of compiling the regex and use the Matcher.find() method to put a boolean value inside a variable, but I wanted to enclose everything in brackets to save memory.
This is my solution:
String regex = "(?:([\\p{IsAlphabetic}]*)?(-[\\p{IsAlphabetic}]+))+";
boolean hasSubSequence;
{
Matcher m = Pattern.compile(regex).matcher(identifier);
hasSubSequence = m.find();
}
if (hasSubSequence) {
Matcher kebabCaseMatches = Pattern.compile(regex).matcher(identifier);
while (kebabCaseMatches.find()) {
String currentOccurence = kebabCaseMatches.group();
while (currentOccurence.contains("-")) {
currentOccurence = currentOccurence.replaceFirst("-[\\p{IsAlphabetic}]", Character.toString(Character.toUpperCase(currentOccurence.charAt(currentOccurence.indexOf("-") + 1))));
}
// "identifier" is the function's argument
identifier = identifier.replaceFirst(regex, currentOccurence);
}
}
Does this really save memory?
Solution 1:[1]
You could compile the pattern once where you declared regex (static final?): would save speed and many instances. Brackets are voodoo.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joop Eggen |
