Skip to content

Commit ba98b72

Browse files
committed
Pre-compile all regexes.
1 parent ef9229a commit ba98b72

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

collector/src/main/java/io/prometheus/jmx/JmxCollector.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ private static class Rule {
4747
List<ObjectName> blacklistObjectNames = new ArrayList<ObjectName>();
4848
ArrayList<Rule> rules = new ArrayList<Rule>();
4949

50+
private static final Pattern snakeCasePattern = Pattern.compile("([a-z0-9])([A-Z])");
51+
5052
public JmxCollector(Reader in) throws IOException, ParseException, MalformedObjectNameException {
5153
this((JSONObject)new JSONParser().parse(in));
5254
}
@@ -136,14 +138,17 @@ class Receiver implements JmxScraper.MBeanReceiver {
136138

137139
private static final char SEP = '_';
138140

141+
private final Pattern unsafeChars = Pattern.compile("[^a-zA-Z0-9:_]");
142+
private final Pattern multipleUnderscores = Pattern.compile("__+");
143+
139144
// [] and () are special in regexes, so swtich to <>.
140145
private String angleBrackets(String s) {
141146
return "<" + s.substring(1, s.length() - 1) + ">";
142147
}
143148

144149
private String safeName(String s) {
145150
// Change invalid chars to underscore, and merge underscores.
146-
return s.replaceAll("[^a-zA-Z0-9:_]", "_").replaceAll("__+", "_");
151+
return multipleUnderscores.matcher(unsafeChars.matcher(s).replaceAll("_")).replaceAll("_");
147152
}
148153

149154
void addSample(MetricFamilySamples.Sample sample, Type type, String help) {
@@ -223,7 +228,7 @@ public void recordBean(
223228
// attrDescription tends not to be useful, so give the fully qualified name too.
224229
String help = attrDescription + " (" + beanName + attrName + ")";
225230

226-
String attrNameSnakeCase = attrName.replaceAll("([a-z0-9])([A-Z])", "$1_$2").toLowerCase();
231+
String attrNameSnakeCase = snakeCasePattern.matcher(attrName).replaceAll("$1_$2").toLowerCase();
227232

228233
for (Rule rule : rules) {
229234
Matcher matcher = null;

0 commit comments

Comments
 (0)