Skip to content

Commit

Permalink
HHH-14305 Introduce new method in CollectionsHelper to reduce size of…
Browse files Browse the repository at this point in the history
… long lived collections
  • Loading branch information
Sanne committed Nov 1, 2020
1 parent 250db69 commit fb34b72
Showing 1 changed file with 69 additions and 0 deletions.
Expand Up @@ -211,4 +211,73 @@ public static boolean isNotEmpty(Map map) {
public static boolean isEmpty(Object[] objects) {
return objects == null || objects.length == 0;
}

/**
* Use to convert sets which will be retained for a long time,
* such as for the lifetime of the Hibernate ORM instance.
* The returned Set might be immutable, but there is no guarantee of this:
* consider it immutable but don't rely on this.
* The goal is to save memory.
* @param set
* @param <T>
* @return
*/
public static <T> Set<T> toSmallSet(Set<T> set) {
switch ( set.size() ) {
case 0:
return Collections.EMPTY_SET;
case 1:
return Collections.singleton( set.iterator().next() );
default:
//TODO assert tests pass even if this is set to return an unmodifiable Set
return set;
}
}

/**
* Use to convert Maps which will be retained for a long time,
* such as for the lifetime of the Hibernate ORM instance.
* The returned Map might be immutable, but there is no guarantee of this:
* consider it immutable but don't rely on this.
* The goal is to save memory.
* @param map
* @param <K>
* @param <V>
* @return
*/
public static <K, V> Map<K, V> toSmallMap(final Map<K, V> map) {
switch ( map.size() ) {
case 0:
return Collections.EMPTY_MAP;
case 1:
Map.Entry<K, V> entry = map.entrySet().iterator().next();
return Collections.singletonMap( entry.getKey(), entry.getValue() );
default:
//TODO assert tests pass even if this is set to return an unmodifiable Map
return map;
}
}

/**
* Use to convert ArrayList instances which will be retained for a long time,
* such as for the lifetime of the Hibernate ORM instance.
* The returned List might be immutable, but there is no guarantee of this:
* consider it immutable but don't rely on this.
* The goal is to save memory.
* @param arrayList
* @param <V>
* @return
*/
public static <V> List<V> toSmallList(ArrayList<V> arrayList) {
switch ( arrayList.size() ) {
case 0:
return Collections.EMPTY_LIST;
case 1:
return Collections.singletonList( arrayList.get( 0 ) );
default:
arrayList.trimToSize();
return arrayList;
}
}

}

0 comments on commit fb34b72

Please sign in to comment.