Skip to content

Issue: Unnecessary runtime regex compilation in version normalization code #560

@kamilkrzywanski

Description

@kamilkrzywanski

In the JetBrains Runtime codebase(not in openJdk), there is a section that repeatedly compiles regular expressions at runtime when normalizing version strings.
This causes unnecessary performance overhead.

Current code example:

String res = Arrays.stream(matcher.group().split("\\."))
        .filter(s -> s.matches("\\d+"))
        .map(s -> s.replaceFirst("^0*", ""))
        .map(s -> s.isEmpty() ? "0" : s)
        .collect(Collectors.joining("."));
return !res.isEmpty() ? res : "0";

Suggested improvement
Use precompiled regex patterns for the two expressions that are repeatedly used:

private static final Pattern DIGITS_ONLY = Pattern.compile("\\d+");
private static final Pattern LEADING_ZEROS = Pattern.compile("^0*");

Updated code:

String res = Arrays.stream(matcher.group().split("\\."))
        .filter(s -> DIGITS_ONLY.matcher(s).matches())
        .map(s -> LEADING_ZEROS.matcher(s).replaceFirst(""))
        .map(s -> s.isEmpty() ? "0" : s)
        .collect(Collectors.joining("."));
return !res.isEmpty() ? res : "0";

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions