开发者

In terms of performance, is an array of doubles better or worse than a custom class in java?

开发者 https://www.devze.com 2023-04-04 22:15 出处:网络
I\'m writing a simple implementation of the GJK algorithm (collision of convex shapes) in Java, and it involves a lot of simple calculations on 3D vectors. In terms of performance vs readability, woul

I'm writing a simple implementation of the GJK algorithm (collision of convex shapes) in Java, and it involves a lot of simple calculations on 3D vectors. In terms of performance vs readability, would it be better to store the points as double[3] and have a whole host of static methods to process them (add, subtract, dot, cross, negate etc) or use a class with the methods contained within?

The problem with the array of doubles is that to do a simple sub开发者_C百科traction (for instance) multiple loops are required if specialised methods are used, or the code becomes very long if they're hard-coded in. A Point object makes the code much more readable, but is it worth it for what I'm assuming is not an insignificant performance overhead?


My suggestion: make it work using whatever takes the least effort on your part, then optimize it later. It may turn out that the bottleneck in your application is something else entirely, and the improvement in the collision detection is but a minor piece.

For example, say you find that your application spends 10% of its time doing collision detection, and 50% of its time doing disk reads. If you can use caching to cut disk reads in half, you've improved execution by 25%, which is more than twice what you could optimally achieve by eliminating the collision detection time altogether.

As Donald Knuth said "premature optimization is the root of all evil."


I would use the object in case you need to perform other function that manipulate, search or edit the data. Maybe your base class can be an array to.


IMHO, the basis tenet of OOP is to have objects defining a contract and fulfilling their responsibility (typically single). So you should definitely go the class way; this will also make your class more maintainable and readable.


Making a class is always better, it this way to can not only acieve readability but you will also achieve extensibility, you can extend the meaning of your class anytime. Before I understand the magic of oops i also use to feel the same but now I real know what differences it can create to my project. You can achieve hell lot of propose from oops.


I think

Point point = new Point(x, y, z);

is more like a point than

double[] point = {x, y, z};

So, go for class!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号