Skip to content

Commit

Permalink
Cache results of Model#shapes(Class<T> type)
Browse files Browse the repository at this point in the history
Some testing revealed that cache for returning shapes of a specific type
has about a 75% cache hit when running :smithy-model:test.
  • Loading branch information
mtdowling committed Apr 23, 2020
1 parent 43eabdf commit bbfa3c4
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions smithy-model/src/main/java/software/amazon/smithy/model/Model.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@
package software.amazon.smithy.model;

import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
Expand Down Expand Up @@ -62,14 +64,18 @@ public final class Model implements ToSmithyBuilder<Model> {

private final Map<String, Node> metadata;

private volatile Map<Shape, TraitDefinition> traitDefinitions;
/** Lazily computed map of trait definitions. */
private Map<Shape, TraitDefinition> traitDefinitions;

/** Cache of computed {@link KnowledgeIndex} instances. */
private final Map<Class<? extends KnowledgeIndex>, KnowledgeIndex> blackboard = new ConcurrentHashMap<>();

/** A map of shape ID to shapes that backs the shape map. */
private final Map<ShapeId, Shape> shapeMap;

/** A cache of shapes of a specific type. */
private final Map<Class<? extends Shape>, Collection<Shape>> cachedTypes = new ConcurrentHashMap<>();

/** Lazily computed hashcode. */
private int hash;

Expand Down Expand Up @@ -245,7 +251,15 @@ public Stream<Shape> shapes() {
*/
@SuppressWarnings("unchecked")
public <T extends Shape> Stream<T> shapes(Class<T> shapeType) {
return (Stream<T>) shapeMap.values().stream().filter(value -> value.getClass() == shapeType);
return (Stream<T>) cachedTypes.computeIfAbsent(shapeType, t -> {
List<Shape> result = new ArrayList<>();
for (Shape shape : shapeMap.values()) {
if (shape.getClass() == shapeType) {
result.add(shape);
}
}
return result;
}).stream();
}

/**
Expand Down

0 comments on commit bbfa3c4

Please sign in to comment.