Home > Enterprise >  Java Private Static vs Private method inside a class
Java Private Static vs Private method inside a class

Time:11-20

Can someone explain in which case we use the private static method or just private method inside a class?

My confusion is coming from they're both private methods anyways so we won't be able to call

them from Outside of the class anyways(which defeats the purpose of ) the keyword static.

CodePudding user response:

the main difference between non static methods and static ones (no matter whether they are private or public) - implicit passing of this to non-static methods as hidden argument

so, even if method is private and can be called only within class itself - ultimately it is performance difference, in number crunching applications it makes measurable difference

here is naïve measurement:

public class Test {
    public static class Calc {
        public long sum1() {
            long r = 0;
            for (long i = 1; i < 10_000_000_000L; i  )
                r  = sum(i, i);
            return r;
        }

        public long sum2() {
            long r = 0;
            for (long i = 1; i < 10_000_000_000L; i  )
                r  = sum_static(i, i);
            return r;
        }

        private long sum(long a, long b) {
            return a   b;
        }

        private static long sum_static(long a, long b) {
            return a   b;
        }
    }

    public static void main(String[] args) {
        final Calc c = new Calc();
        final long t1 = System.currentTimeMillis();
        for (int i = 0; i < 10; i  )
            System.out.println(c.sum1());
        final long t2 = System.currentTimeMillis();
        for (int i = 0; i < 10; i  )
            System.out.println(c.sum2());
        final long t3 = System.currentTimeMillis();

        System.out.println("non static "   (t2 - t1));
        System.out.println("    static "   (t3 - t2));
    }
}

static version is approximately 10% faster (YMMV)

  • Related