Skip to content

Commit

Permalink
Improve {Abstract,Mutable}KeySet.iterator() memory overhead
Browse files Browse the repository at this point in the history
Do not use an anonymous class, but rather a dedicated nested class,
which reduces the need to capture 'this', which we do not really need.
This translates to 8 bytes saved on typical use.

Signed-off-by: Robert Varga <[email protected]>
(cherry picked from commit 9962d4e)
  • Loading branch information
rovarga committed Apr 13, 2023
1 parent a412968 commit 9c4c6b2
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 31 deletions.
32 changes: 19 additions & 13 deletions triemap/src/main/java/tech/pantheon/triemap/AbstractKeySet.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,18 +78,24 @@ public final Spliterator<K> spliterator() {
abstract int spliteratorCharacteristics();

final Iterator<K> immutableIterator() {
return new Iterator<K>() {
private final ImmutableIterator<K, ?> itr = map().immutableIterator();

@Override
public boolean hasNext() {
return itr.hasNext();
}

@Override
public K next() {
return itr.next().getKey();
}
};
return new Itr<>(map().immutableIterator());
}

private static final class Itr<K> implements Iterator<K> {
private final ImmutableIterator<K, ?> delegate;

Itr(final ImmutableIterator<K, ?> delegate) {
this.delegate = delegate;
}

@Override
public boolean hasNext() {
return delegate.hasNext();
}

@Override
public K next() {
return delegate.next().getKey();
}
}
}
42 changes: 24 additions & 18 deletions triemap/src/main/java/tech/pantheon/triemap/MutableKeySet.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,24 +32,7 @@ final class MutableKeySet<K> extends AbstractKeySet<K> {

@Override
public Iterator<K> iterator() {
return new Iterator<K>() {
private final AbstractIterator<K, ?> itr = map().iterator();

@Override
public boolean hasNext() {
return itr.hasNext();
}

@Override
public K next() {
return itr.next().getKey();
}

@Override
public void remove() {
itr.remove();
}
};
return new Itr<>(map().iterator());
}

@Override
Expand All @@ -67,4 +50,27 @@ public boolean remove(final Object o) {
int spliteratorCharacteristics() {
return Spliterator.DISTINCT | Spliterator.CONCURRENT | Spliterator.NONNULL;
}

private static final class Itr<K> implements Iterator<K> {
private final AbstractIterator<K, ?> delegate;

Itr(final AbstractIterator<K, ?> delegate) {
this.delegate = delegate;
}

@Override
public boolean hasNext() {
return delegate.hasNext();
}

@Override
public K next() {
return delegate.next().getKey();
}

@Override
public void remove() {
delegate.remove();
}
}
}

0 comments on commit 9c4c6b2

Please sign in to comment.