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.

Simeon
  • 7,582
  • 15
  • 64
  • 101
  • 9
    have you tried it? Was it faster? – Alnitak Mar 05 '13 at 14:39
  • Static methods can only access static fields of the class, since those are fields and method that aren't associated with a particular instance but with the class itself. Any change made to those fields by those methods are reflected on *every* instance of the class. Keep that in mind when using them. The good thing is that you don't need an instance of a class to use them, just measure the consequences of such a behaviour. – Fritz Mar 05 '13 at 14:40
  • Have you googled it? Have you [SO]gled it? – ppeterka Mar 05 '13 at 14:40
  • 1
    I'd say the speed difference (whatever it is) wouldn't be worth the trade off of which one is more readable. – David Mar 05 '13 at 14:40
  • I have not, I was actually hoping that the compiler would do it for me :) Besides I don't think I can make anything other than a micro benchmark on this and it probably wouldn't say much. – Simeon Mar 05 '13 at 14:41
  • 1
    This is unrelated to peformance, but using static methods is a bad idea if you want to unit test your code http://stackoverflow.com/questions/11591564/why-are-static-methods-untestable – naomi Mar 05 '13 at 14:41
  • If you don't use any instance variables in the convenience method I'd put it in a static method in case it's convenient elsewhere later on. – ldam Mar 05 '13 at 14:41
  • @naomi awesome point about unit tests. – Simeon Mar 05 '13 at 14:43
  • 1
    @david99world and which is more readable ? – Simeon Mar 05 '13 at 14:47
  • @naomi: Static methods are testable. In fact, the author of each response that you linked to said the same. – splungebob Mar 05 '13 at 14:55
  • 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. – Theodoros Chatzigiannakis Mar 05 '13 at 15:29

8 Answers8

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.

  • agreed, I tested, there were no significant difference. – CsBalazsHungary Mar 05 '13 at 15:56
  • 1
    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). – Vinicius Seufitele May 30 '14 at 14:08
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
Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • It doesn't it uses arguments only (as I have shown in the code snippet). This is not what I'm asking :) – Simeon Mar 05 '13 at 14:42
  • 1
    so make it static, and don't worry about the (almost certainly) negligible performance differences. – Alnitak Mar 05 '13 at 14:43
  • I'm not worrying :) I want to know if there is a difference. Don't worry is still not an answer IMHO. – Simeon Mar 05 '13 at 14:45
  • @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. – naomi Mar 05 '13 at 14:51
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.

cHao
  • 84,970
  • 20
  • 145
  • 172
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.

Nilesh Tailor
  • 146
  • 2
  • 6
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.

Aman J
  • 1,825
  • 1
  • 16
  • 30
  • This type of answers are what I'm looking for. Thanks. – Simeon Mar 05 '13 at 14:48
  • 2
    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 Mar 05 '13 at 14:48
  • 2
    @cHao you are right but private non-static methods use `static/early binding` – Aman J Mar 05 '13 at 15:14
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.

parsifal
  • 121
  • 2
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.

CsBalazsHungary
  • 803
  • 14
  • 30
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.

PRIBAN91
  • 87
  • 3
  • 12