Skip to content

Commit

Permalink
Optimize KClass creation from Class instance
Browse files Browse the repository at this point in the history
Don't create unnecessary iterator every time in HashPMap.get (see
hrldcpr/pcollections#41). Also fix a warning and remove
misleading comment
  • Loading branch information
udalov committed Sep 5, 2016
1 parent d0d1824 commit f4a1aa6
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ internal fun <T : Any> getOrCreateKotlinClass(jClass: Class<T>): KClassImpl<T> {
@Suppress("UNCHECKED_CAST")
val kClass = cached.get() as KClassImpl<T>?
if (kClass?.jClass == jClass) {
return kClass!!
return kClass
}
}
else if (cached != null) {
Expand All @@ -51,7 +51,6 @@ internal fun <T : Any> getOrCreateKotlinClass(jClass: Class<T>): KClassImpl<T> {
// This is the most unlikely case: we found a cached array of references of length at least 2 (can't be 1 because
// the single element would be cached instead), and none of those classes is the one we're looking for
val size = cached.size
// Don't use Array constructor because it creates a lambda
val newArray = arrayOfNulls<WeakReference<KClassImpl<*>>>(size + 1)
// Don't use Arrays.copyOf because it works reflectively
System.arraycopy(cached, 0, newArray, 0, size)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ public static <E> ConsPStack<E> empty() {
return (ConsPStack<E>) EMPTY;
}

private final E first;
private final ConsPStack<E> rest;
final E first;
final ConsPStack<E> rest;
private final int size;

private ConsPStack() { // EMPTY constructor
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public final class HashPMap<K, V> {
@SuppressWarnings("unchecked")
@NotNull
public static <K, V> HashPMap<K, V> empty() {
return (HashPMap<K, V>) HashPMap.EMPTY;
return (HashPMap<K, V>) EMPTY;
}

private final IntTreePMap<ConsPStack<MapEntry<K, V>>> intMap;
Expand All @@ -49,9 +49,12 @@ public boolean containsKey(Object key) {

public V get(Object key) {
ConsPStack<MapEntry<K, V>> entries = getEntries(key.hashCode());
for (MapEntry<K, V> entry : entries)
while (entries != null && entries.size() > 0) {
MapEntry<K, V> entry = entries.first;
if (entry.key.equals(key))
return entry.value;
entries = entries.rest;
}
return null;
}

Expand Down Expand Up @@ -86,9 +89,11 @@ private ConsPStack<MapEntry<K, V>> getEntries(int hash) {

private static <K, V> int keyIndexIn(ConsPStack<MapEntry<K, V>> entries, Object key) {
int i = 0;
for (MapEntry<K, V> entry : entries) {
while (entries != null && entries.size() > 0) {
MapEntry<K, V> entry = entries.first;
if (entry.key.equals(key))
return i;
entries = entries.rest;
i++;
}
return -1;
Expand Down

0 comments on commit f4a1aa6

Please sign in to comment.