Mutable or immutable vectors?

Just wondering what type of vectors (the mathematical kind) people use. The mutable vectors would appear to have a slight performance edge, but at the cost of safety. I am currently working on some collision detection code, and haven’t decided which I want to use. At the moment, I am doing some stress testing and using immutable vectors. At the current performance limit (which may not be bound by object creation), around 100,000,000 vectors (2D) are being created a second. Not too bad. What experinces have all of you had with mutable and immutable objects and object creation?

That level of garbage is likely to be a big problem, to be honest.

Cas :slight_smile:

I would have thought so as well, but maybe the JIT compiler is being smart. Most of the objects are short lived and may be added to the stack rather than the heap. I am running OpenJDK 1.6.0_20 on a Linux machine.

And a mistake in my original post, it is 50,000,000 objects/second. I forgot that I was actually being smart when I wrote the test and was not testing symmetric collisions.

No stack allocation in JDK1.6 I’m afraid. So it’s likely to get a bit jittery. I use mutable stuff all over the place, and, cough splutter embarrassment, static finals as “scratch” areas to reuse.

Cas :slight_smile:

not applyable for all usecases: but what i did is to use nio bytebuffers for vector/matrix storage and do the computation on the gpu/cpu/ via JOCL. Memory is static in my case. Accessing the data from java is a bit slower however.

Yar, still no mapped ByteBuffers. Grr.

Cas :slight_smile:

I wrote a vector library that had all the math logic defined in read-only types, and they took a mutable subtype as a result parameter (so you could pass in null to create a new one, or re-use an existing object for intermediate computations). This gave me some flexibility so I can have a matrix return a read-only vector over their column or row and have that mirror any changes to the matrix.

I don’t know if my abstractions are hurting my performance, currently the graphics is still such a bottleneck that it’s hard to tell. I did end up unboxing certain vector operations in my physics engine in the inner loops of an iterating constraint solver, but that’s a very specific, performance intense operation.

In my high-level game objects, having them expose read-only types makes it easy for them to know when their transform or rotation or color has been changed and push out notifications. This means my game loop has to do less work for each object and can just ask it if it’s been updated instead of not knowing if something has been changed underneath it.