3

What I'm asking is whether there is a difference between doing this:

public Something importantBlMethod(SomethingElse arg) {
    if (convenienceCheckMethod(arg)) {
        // do important BL stuff
    }
}

private boolean convenienceCheckMethod(SomethingElse arg) {
    // validate something
}

And this:

public Something importantBlMethod(SomethingElse arg) {
    if (convenienceCheckMethod(arg)) {
        // do important BL stuff
    }
}

private static boolean convenienceCheckMethod(SomethingElse arg) {
    // validate something
}

I actually use option 1 as it seems more natural to me.

So is there a style/convention/performance difference between the first and the second way ?

Thanks,


As suggested in the comments I tested it, in my benchmarks the dynamic method is faster.

This is the test code:

public class Tests {

    private final static int ITERATIONS = 100000;

    public static void main(String[] args) {
        final long start = new Date().getTime();

        final Service service = new Service();
        for (int i = 0; i < ITERATIONS; i++) {

            service.doImportantBlStuff(new SomeDto());
        }

        final long end = new Date().getTime();

        System.out.println("diff: " + (end - start) + " millis");
    }
}

This is the service code:

public class Service {

    public void doImportantBlStuff(SomeDto dto) {

        if (checkStuffStatic(dto)) {

        }

        // if (checkStuff(dto)) {

        // }
    }

    private boolean checkStuff(SomeDto dto) {
        System.out.println("dynamic");
        return true;
    }

    private static boolean checkStuffStatic(SomeDto dto) {
        System.out.println("static");
        return true;
    }
}

For 100000 iterations the dynamic method passes for 577ms, the static 615ms.

This however is inconclusive for me since I don't know what and when the compiler decides to optimize.

This is what I'm trying to find out.

11
  • 9
    have you tried it? Was it faster? Commented Mar 5, 2013 at 14:39
  • 1
    I'd say the speed difference (whatever it is) wouldn't be worth the trade off of which one is more readable. Commented Mar 5, 2013 at 14:40
  • 1
    This is unrelated to peformance, but using static methods is a bad idea if you want to unit test your code stackoverflow.com/questions/11591564/… Commented Mar 5, 2013 at 14:41
  • 1
    @david99world and which is more readable ? Commented Mar 5, 2013 at 14:47
  • 3
    I'd say that's not the case, because a private method is essentially final too and, therefore, just as statically callable and inlineable as a static one. Commented Mar 5, 2013 at 15:29

8 Answers 8

7

Performance wise: The difference, if any, is negligible.

The rule of thumb is to declare your method static if it doesn't interact with any members of its class.

Sign up to request clarification or add additional context in comments.

2 Comments

agreed, I tested, there were no significant difference.
I'd like to point out that private methods have the same performance as static because they can be determined at compile time (the compiler know that private methods won't be overriden). If you mark the method as public, then the dispatch will be at runtime, and will be slower than the static method (though by a little margin).
2

If the result of the function does not depend on anything but the arguments, it should be static. If it depends on an instance, make it an instance member.

It's not about performance; it's about semantics. Unless you're calling this function a million times a second, you will not notice a performance difference, and even then the difference won't be significant.

Comments

2

It all depends on the context. Generally static methods/variables are declared in a class so that an external class can make use of them.

If you are making a call to a local method then you should generally use instance methods rather than making static calls.

FYI, your syntax for calling the static method from an instance method is wrong. You have to supply the class name.

2 Comments

You are correct about the coding style, but this is unrelated to the question.
I agree, that's why I put it up as an FYI.
2

If your method requires instance data or calls to other instance methods, it must be an instance method.

If the function only depends on its arguments, and no other static data, then it might as well be an instance method too - you'll avoid the need to repeat the class name when you invoke the static function.

IMHO, there's no particular need to make the function static unless:

  1. it's callable from other classes (i.e. not private), and
  2. it doesn't refer to instance variables, and
  3. it refers to other static class data

4 Comments

It doesn't it uses arguments only (as I have shown in the code snippet). This is not what I'm asking :)
so make it static, and don't worry about the (almost certainly) negligible performance differences.
I'm not worrying :) I want to know if there is a difference. Don't worry is still not an answer IMHO.
@Alnitak, I'd add add a couple more criteria to your list: 3. You don't ever intend to stub it for a unit test, and 4. There are good reasons NOT to make it an instance method of the class of its main parameter.
2

It might, it might not. It might be different between different executions of your code.

Here's the only thing that you can know without digging into the Hotsport code (or the code of your non-Hotspot JVM):

  • The static method is invoked with invokestatic, which does not require an object reference.
  • The instance private method is invoked with invokespecial, which does require an object reference.

Both of those opcodes have a process for resolving the actual method to invoke, and those processes are relatively similar (you can read the specs). Without counting the instructions of an actual implementation, it would be impossible to say which is faster.

The invokespecial pushes an extra value onto the stack. The time to do this is counted in fractions of a nanosecond.

And making all of this moot, Hotspot has a wide range of optimizations that it can perform. It probably doesn't have to do the actual method resolution more than once during your program's run. It might choose to inline the method (or it might not), but that cost would again be roughly equivalent.

Comments

2

According to me NO binding of static method is same as non-static private i.e early binding. . Compiler actually adds code of method (static or non-static private) to your code while creating it's byte code.

Update : Just came through this article. It says instance methods binding is dynamic so if method is not non-static private then. Your static method is faster.

3 Comments

This type of answers are what I'm looking for. Thanks.
Not quite the same. Instance methods involve a bit more in terms of finding the right function to call at runtime, unless the method or class is final.
@cHao you are right but private non-static methods use static/early binding
1

I checked, I hope it does what you wanted to know, the code won't be beautiful:

public class main {

@SuppressWarnings("all")
public static void main(String[] args) {
    main ma = new main();
    int count = Integer.MAX_VALUE;
    long beg = (new Date()).getTime();
    for (int i = 0; i < count; i++) {
        ma.doNothing();
    }
    System.out.println("priv : " + new Long((new Date()).getTime() - beg).toString());

    beg = (new Date()).getTime();
    for (int i = 0; i < count; i++) {
        doNothingStatic();
    }
    System.out.println("privstat : " + new Long((new Date()).getTime() - beg).toString());

}

private void doNothing() {
    int i = 0;
}

private static void doNothingStatic() {
    int i = 0;
}
}

results:

priv : 1774
privstat : 1736

priv : 1906
privstat : 1783

priv : 1963
privstat : 1751

priv : 1782
privstat : 1929

priv : 1876
privstat : 1867

It doesn't look like dependent on static - nonstatic private method. I am sure the differences are coming from the current burden of the machine.

Comments

1

I take part in coding competitions and I have observed, that non-static methods are faster(however minimal) than the static methods. Of course, it depends on your use and the what the situation demands, but the static methods gives poorer performance as compared to non-static ones. By convention, you can use static methods for the ease of code, but creating an instance of the class and calling the method will give better performance.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.