How to make my List.filter faster on Scala?

I am making a game with Scala.

In my game there are several pools for storing enemies. They are immutable lists because they are initialized to a size that should be sufficient (because creating new copies of the enemy during the game is very expensive).

My game knows if the enemy is alive by asking enemy.isVisible. Therefore my CollisionHandler works like:

  • Unite all living enemies in a list
  • Get live bullets
  • Spatial partition and collision detection for bullets and enemies in the same space.

What pushed me was that according to the profiler, step 1 takes up most of the time. And what this step does is basically say:

def allActiveEnemies = List(enemyType1.getAllActive, enemyType2.getAllActive, ... ).flatten

flattenthere doesn’t seem expensive, but instead it gets getAllActive calls. They are implemented in my combined form as follows:

trait Pooled[T <: Entity] {
    var pool = List[T]()
    val INITIAL_POOL_SIZE:Int

    def initPool() {
        for(i<-1 to INITIAL_POOL_SIZE)
        {
            addToPool(disable(createNew))
        }
    }

    def getAllActive:List[T] = pool.filter(e => e.isVisible)
}

(I missed most of this trait because I don't think it matters here.)

pool.filter is something that burns like 45% of the total time spent at CollisionHandler, which seems really weird.

Any suggestions to make here faster?

Maybe using ArrayLists instead of List? Maybe with some sorting and mutable collections? Or am I just doing something terribly wrong?

Thank!

+5
source share
1 answer

? , , , . , (.. pool.view.filter(e => e.isVisible), Seq[T]). , , , . Set - ; , .

+4

All Articles