Skip to content

Commit

Permalink
Add a simple cache for ComparableVersions
Browse files Browse the repository at this point in the history
This can improve performance in pathetic corner cases by up to 50%.
  • Loading branch information
TobiX authored and slawekjaranowski committed Dec 21, 2022
1 parent 2d7a157 commit 2bed457
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public int compareTo(ArtifactVersion other) {
return -1;
}

return comparator.compareTo(new ComparableVersion(other.toString()));
return comparator.compareTo(ComparableVersion.of(other.toString()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.concurrent.ConcurrentHashMap;

/**
* Generic implementation of version comparison.
Expand All @@ -37,6 +39,8 @@
* Note: The implementation of the maven core should be used.
*/
public class ComparableVersion implements Comparable<ComparableVersion> {
private static final Map<String, ComparableVersion> CACHE = new ConcurrentHashMap<>();

private String value;

private String canonical;
Expand Down Expand Up @@ -283,7 +287,17 @@ public String toString() {
}
}

public ComparableVersion(String version) {
/**
* Get a ComparableVersion representing the version in a string.
*/
public static ComparableVersion of(String version) {
return CACHE.computeIfAbsent(version, ComparableVersion::new);
}

/**
* Create a ComparableVersion from a string. Try to avoid using this and instead use the cache by calling {@link #of(String)}
*/
protected ComparableVersion(String version) {
parseVersion(version);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public int compare(ArtifactVersion o1, ArtifactVersion o2) {
if (o1 instanceof BoundArtifactVersion) {
return o1.compareTo(o2);
}
return new ComparableVersion(o1.toString()).compareTo(new ComparableVersion(o2.toString()));
return ComparableVersion.of(o1.toString()).compareTo(ComparableVersion.of(o2.toString()));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public class MercuryVersionComparator extends AbstractVersionComparator {
* {@inheritDoc}
*/
public int compare(ArtifactVersion o1, ArtifactVersion o2) {
return new ComparableVersion(o1.toString()).compareTo(new ComparableVersion(o2.toString()));
return ComparableVersion.of(o1.toString()).compareTo(ComparableVersion.of(o2.toString()));
}

protected int innerGetSegmentCount(ArtifactVersion v) {
Expand Down

0 comments on commit 2bed457

Please sign in to comment.