Java best practices in matrix / vector library

I need to write a simple vector / matrix library for a small geometry project I'm working on. that’s what interests me.

when performing mathematical operations on vectors in the java environment, is it better to return a new instance of the vector or change the state of the original.

I saw him back and forth and would like to get a majority entry.

some people say that vectors should be immutable, and static methods should be used to create new ones, others say that they should be mutable, and normal methods should be used to change their state. I saw this in some cases, when the object is immutable, and normal methods are called, which returns a new vector from the object without changing the state - it seems to be a little from me.

I just wanted to feel if there is any best practice for this - I imagine what has been done a million times, and I'm really wondering if there is a standard way to do this.

I noticed that the apache commons math library returns a new vector every time from the original.

+7
source share
2 answers

How important is performance? Is vector arithmetic a large component so that it affects the performance of the entire system?

If this is not the case, and there will be a lot of concurrency, then immutable vectors will be useful because they reduce concurrency problems.

If there are a lot of mutations on vectors, then the overhead of new objects that immutable vectors need will become significant, and it may be better to have mutable vectors and make concurrency the hard way.

+5
source

It depends. Generally speaking, immutability is better.

First of all, it is automatically thread safe. Easier to maintain and test.

However, sometimes you need speed when creating new instances takes too much time.

(Note: if you are not 100% positive, you need such a number of revolutions, you do not need it. Think of high-frequency trading and applications with intensive math in real time. And although you should just go first and optimize later.)

As for static vs normal methods, after good OOP principles you shouldn't have static methods. To create new vectors / matrices, you can use the constructor.

Then what is your support structure? Best of all, probably one-dimensional arrays of twins for vectors and multi-dimensional arrays of twins for matrices. This at least allows you to stay relatively fast using primitive objects.

If you get to the point where you need even more performance, you can add modifiers to your vector / matrix that can change the backup data. You can even decide that the dimensions are unchangeable, but the contents are resized, which will also give you some other security measures.

+1
source

All Articles