Skip to content

Commit 3010d83

Browse files
committed
400% performance gain
1 parent 496b22e commit 3010d83

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.lambda.util.collections
2+
3+
/**
4+
* Filters elements of the iterable by their runtime type and a predicate, and adds the matching elements to the specified mutable collection.
5+
*
6+
* This function allows filtering elements of an iterable based on their runtime type and a provided predicate function.
7+
* The elements that match both the type constraint and the predicate are added to the destination mutable collection.
8+
* Because we do not want additional overhead, this function acts as pointer receiver to a collection.
9+
* The predicate function determines whether an element should be included based on its type and any additional criteria.
10+
*
11+
* @param R The target type to filter elements to.
12+
* @param C The type of the destination mutable collection.
13+
* @param destination The mutable collection to which the filtered elements will be added.
14+
* @param predicate The predicate function that determines whether an element should be included based on its type and other criteria.
15+
*/
16+
inline fun <reified R, C : MutableCollection<in R>> Iterable<*>.filterIsInstanceTo(
17+
destination: C,
18+
predicate: (R) -> Boolean
19+
) {
20+
for (element in this) if (element is R && predicate(element)) destination.add(element)
21+
}

common/src/main/kotlin/com/lambda/util/world/EntityUtils.kt

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.lambda.util.world
22

33
import com.lambda.context.SafeContext
4+
import com.lambda.util.collections.filterIsInstanceTo
45
import net.minecraft.entity.Entity
56
import net.minecraft.util.math.ChunkSectionPos
67
import net.minecraft.util.math.Vec3d
@@ -48,7 +49,7 @@ object EntityUtils {
4849
val sectionY = pos.y.toInt() shr 4
4950
val sectionZ = pos.z.toInt() shr 4
5051

51-
val entities = mutableListOf<T>()
52+
val entities = ArrayList<T>()
5253

5354
// Here we iterate over all sections within the specified distance and add all entities of type [T] to the list.
5455
// We do not have to worry about performance here, as the number of sections is very limited.
@@ -57,7 +58,7 @@ object EntityUtils {
5758
for (y in sectionY - chunks..sectionY + chunks) {
5859
for (z in sectionZ - chunks..sectionZ + chunks) {
5960
val section = world.entityManager.cache.findTrackingSection(ChunkSectionPos.asLong(x, y, z)) ?: continue
60-
entities.addAll(section.collection.getAllOfType(T::class.java).filter(predicate))
61+
section.collection.filterIsInstanceTo(entities, predicate)
6162
}
6263
}
6364
}

0 commit comments

Comments
 (0)