Skip to content

Commit 6817009

Browse files
committed
[PATCH] Avoid redundant HashMap.containsKey call in java.util.regex{Matcher, Pattern}
Pattern.namedGroupsMap and Matcher.namedGroups contains only non-null values. It means instead of separate containsKey+get calls, we can use single HashMap.get call and then compare result with null. Result code is a bit simpler and faster.
1 parent 314db55 commit 6817009

File tree

2 files changed

+7
-5
lines changed

2 files changed

+7
-5
lines changed

src/java.base/share/classes/java/util/regex/Matcher.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1819,9 +1819,10 @@ char charAt(int i) {
18191819
int getMatchedGroupIndex(String name) {
18201820
Objects.requireNonNull(name, "Group name");
18211821
checkMatch();
1822-
if (!namedGroups().containsKey(name))
1822+
Integer index = namedGroups().get(name);
1823+
if (index == null)
18231824
throw new IllegalArgumentException("No group with name <" + name + ">");
1824-
return namedGroups().get(name);
1825+
return index;
18251826
}
18261827

18271828
private void checkGroup(int group) {

src/java.base/share/classes/java/util/regex/Pattern.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2612,14 +2612,15 @@ private int escape(boolean inclass, boolean create, boolean isrange) {
26122612
if (read() != '<')
26132613
throw error("\\k is not followed by '<' for named capturing group");
26142614
String name = groupname(read());
2615-
if (!namedGroupsMap().containsKey(name))
2615+
Integer index = namedGroupsMap().get(name);
2616+
if (index == null)
26162617
throw error("named capturing group <" + name + "> does not exist");
26172618
if (create) {
26182619
hasGroupRef = true;
26192620
if (has(CASE_INSENSITIVE))
2620-
root = new CIBackRef(namedGroupsMap().get(name), has(UNICODE_CASE));
2621+
root = new CIBackRef(index, has(UNICODE_CASE));
26212622
else
2622-
root = new BackRef(namedGroupsMap().get(name));
2623+
root = new BackRef(index);
26232624
}
26242625
return -1;
26252626
case 'l':

0 commit comments

Comments
 (0)