Search code examples
javastaticfloating-pointpool

Is there some sort of pool in Java that avoids repeating recents arithmetic operations?


I have the three following methods:

 public static void test1(Point point)
    {
        Handler.doSomething(point.x / 2.0f, point.y / 1.75f);
    }

    public static void test2(Point point)
    {
        Handler.doSomething(point.x / 2.0f, point.y / 0.55f);
    }

    public static void test3(Point point)
    {
        Handler.doSomething(point.x / 2.0f, point.y / 1.25f);
    }

Each time one of these methods is called the divisions are performed. Is there some sort of pool in Java that avoids repeating recents arithmetic operations? Because if there isn't one, then maybe it would be preferable to save the results the first time so that I can avoid doing this divisions multiple times? For instance I know for a fact that Java has String pool.


Solution

  • To quote Effective Java 3rd Edition by Josh Bloch, Item 6 ("Avoid creating necessary objects"):

    ... avoiding object creation by maintaining your own object pool is a bad idea unless the objects in the pool are extremely heavyweight [such as a database connection] ... Generally speaking, however, maintaining your own object pools clutters your code, increases memory footprint, and harms performance. Modern JVM implementations have highly optimized garbage collectors that easily outperform such object pools on lightweight objects

    Arithmetic operations are cheap, even if you do them repeatedly. JVM optimizations may avoid even creating objects in some circumstances.

    So, don't try to use an object pool until you have evidence that your program would benefit from one.