What is the gain from declaring a method as static

JavaOptimizationCoding StyleStatic

Java Problem Overview


I've recently been looking through my warnings in Eclipse and come across this one:

static warning

It will give a compiler warning if the method can be declared as static.

[edit] Exact quote within the Eclipse help, with stress on private and final:

> When enabled, the compiler will issue an error or a warning for > methods which are private or final and which refer only to static > members.

Yes I know I can turn it off, but I want to know the reason for turning it on?

Why would it be a good thing to declare every method possible as static?

Will this give any performance benefits? (in a mobile domain)

Pointing out a method as static, I suppose is showing that you don't use any instance variables therefore could be moved to a utils style class?

At the end of the day should I just turn this off 'ignore' or should I fix the 100+ warnings it has given me?

Do you think this is just extra keywords that dirty the code, as the compiler will just inlines these methods anyway? (kind of like you don't declare every variable you can final but you could).

Java Solutions


Solution 1 - Java

Whenever you write a method, you fulfill a contract in a given scope. The narrower the scope is, the smaller the chance is that you write a bug.

When a method is static, you can't access non-static members; hence, your scope is narrower. So, if you don't need and will never need (even in subclasses) non-static members to fulfill your contract, why give access to these fields to your method? Declaring the method static in this case will let the compiler check that you don't use members that you do not intend to use.

And moreover, it will help people reading your code understand the nature of the contract.

That's why it's considered good to declare a method static when it's actually implementing a static contract.

In some cases, your method only means something relative to an instance of your class, and it happens that its implementation doesn't actually use any non-static field or instance. In such cases, you would not mark the method static.

Examples of where you would not use the static keyword:

  • An extension hook which does nothing (but could do something with instance data in a subclass)
  • A very simple default behavior meant to be customisable in a subclass.
  • Event handler implementation: implementation will vary with the class of the event handler but will not use any property of the event handler instance.

Solution 2 - Java

There is no concept with optimization here.

A static method is static because you explicitly declare that method doesn't rely on any instance the enclosing class just because it doesn't need to. So that Eclipse warning, as stated in documentation:

> When enabled, the compiler will issue an error or a warning for methods which are private or final and which refer only to static members.

If you don't need any instance variable and your method is private (can't be called from outside) or final (can't be overriden) then there is no reason to let it be a normal method instead that a static one. A static method is inherently safer even just because you are allowed to do less things with it (it doesn't need any instance, you don't have any implicit this object).

Solution 3 - Java

I've no info on the performance, I suppose it is marginally better at most, since the code does not need to do dynamic dispatch based on the type.

However, a much stronger argument against refactoring into static methods is that currently using static is considered bad practice. Static methods / variables do not integrate well into an object oriented language and also, hard to test properly. This is the reason why some newer languages forego the concept of static methods/variables altogether, or try to internalize it into the language in a way that plays better with OO (eg Objects in Scala).

Most of the time, you need static methods to implement functions that are only using parameters as an input and producing an output using that (eg utility/helper functions) In modern languages, there is a first class Function concept that allows that, so static is not needed. Java 8 will have lambda expressions integrated, so we are moving into this direction already.

Solution 4 - Java

1. Declaring method static gives slight performance benefit, but what is more useful, it allows using it without having an object instance at hand (think of for example about factory method or getting a singleton). It also serves the documentational purpose of telling the nature of the method. This documentational purpose should not be ignored, as it gives immediate hint about the nature of the method to the readers of the code and users of the API and also serves as a tool of thinking for the original programmer - being explicit about the intended meaning helps you also think straight and produce better quality code (I think based on my personal experience, but people are different). For example, it is logical and hence desirable to distinguish between methods operating on a type and methods acting on an instance of the type (as pointed out by Jon Skeet in his comment to a C# question).

Yet another use case for static methods is to mimic procedural programming interface. Think of java.lang.System.println() class and the methods and attributes therein. The class java.lang.System is used like a grouping name space rather than an instantiable object.

2. How can Eclipse (or any other programmed or other kind of - biocomposable or non-biocomposable - entity) know for sure which method could be declared as static? Even if a base class is not accessing instance variables or calling non-static methods, by the mechanism of inheritance the things can change. Only if the method cannot be overridden by inheriting subclass, can we claim with 100% certainty that the method really can be declared static. Overriding a method is impossible exactly in the two cases of being

  1. private (no subclass can use it directly and does not even in principle know about it), or
  2. final (even if accessible by the subclass, there is no way to change the method to refer to instance data or functions).

Hence the logic of the Eclipse option.

3. The original poster also asks: "Pointing out a method as static, I suppose is showing that you don't use any instance variables therefore could be moved to a utils style class?" This is a very good point. Sometimes this kind of design change is indicated by the warning.

It is very useful an option, which I would personally make sure to enable, were I to use Eclipse and were I to program in Java.

Solution 5 - Java

See Samuel's answer on how the scope of the method changes. I guess, this is the main aspect of making a method static.

You also asked about performance:

There might be a tiny performance gain, because a call to a static method does not need the implicit "this" reference as parameter.

However, this performance impact is really tiny. Therefore, it's all about the scope.

Solution 6 - Java

From the Android Performance guidelines:

> Prefer Static Over Virtual If you don't need to access an object's > fields, make your method static. Invocations will be about 15%-20% > faster. It's also good practice, because you can tell from the method > signature that calling the method can't alter the object's state.

http://developer.android.com/training/articles/perf-tips.html#PreferStatic

Solution 7 - Java

Well, the Eclipse documentation says about the warning in question:

> Method can be static > > When enabled, the compiler will issue an error or a warning for > methods which are private or final and which refer only to static > members

I think it pretty much says it all. If the method is private and final and only refers to static members, the method in question might just as well be declared static and by this, make evident that we only intend to access static content from it.

I honestly don't think there is any other mysterious reason behind it.

Solution 8 - Java

I was missing some numbers for the speed differences. So I tried to benchmark them which turned out to be not so easy: https://stackoverflow.com/questions/24882946/java-loop-gets-slower-after-some-runs-jits-fault?noredirect=1#comment38666050_24882946

I finally used Caliper and the results are the same as running my tests by hand:

There is no measurable difference for static/dynamic calls. At least not for Linux/AMD64/Java7.

The Caliper Results are here: https://microbenchmarks.appspot.com/runs/1426eac9-36ca-48f0-980f-0106af064e8f#r:scenario.benchmarkSpec.methodName,scenario.vmSpec.options.CMSLargeCoalSurplusPercent,scenario.vmSpec.options.CMSLargeSplitSurplusPercent,scenario.vmSpec.options.CMSSmallCoalSurplusPercent,scenario.vmSpec.options.CMSSmallSplitSurplusPercent,scenario.vmSpec.options.FLSLargestBlockCoalesceProximity,scenario.vmSpec.options.G1ConcMarkStepDurationMillis

and my own results are:

Static: 352 ms
Dynamic: 353 ms
Static: 348 ms
Dynamic: 349 ms
Static: 349 ms
Dynamic: 348 ms
Static: 349 ms
Dynamic: 344 ms

The Caliper Test class was:

public class TestPerfomanceOfStaticMethodsCaliper extends Benchmark {

	public static void main( String [] args ){
		
		CaliperMain.main( TestPerfomanceOfStaticMethodsCaliper.class, args );
	}
	
	public int timeAddDynamic( long reps ){
		int r=0;
		for( int i = 0; i < reps; i++ ) {
			r |= addDynamic( 1, i );
		}
		return r;
	}
	
	public int timeAddStatic( long reps ){
		int r=0;
		for( int i = 0; i < reps; i++ ) {
			r |= addStatic( 1, i );
		}
		return r;
	}
	
	public int addDynamic( int a, int b ){
	
		return a+b;
	}
	
	private static int addStatic( int a, int b ){
	
		return a+b;
	}
	
}

And my own Test class was:

public class TestPerformanceOfStaticVsDynamicCalls {
	
	private static final int RUNS = 1_000_000_000;

	public static void main( String [] args ) throws Exception{
		
		new TestPerformanceOfStaticVsDynamicCalls().run();
	}
	
	private void run(){

        int r=0;
        long start, end;

        for( int loop = 0; loop<10; loop++ ){

            // Benchmark

            start = System.currentTimeMillis();
            for( int i = 0; i < RUNS; i++ ) {
                r += addStatic( 1, i );
            }
            end = System.currentTimeMillis();
            System.out.println( "Static: " + ( end - start ) + " ms" );

            start = System.currentTimeMillis();
            for( int i = 0; i < RUNS; i++ ) {
                r += addDynamic( 1, i );
            }
            end = System.currentTimeMillis();
            System.out.println( "Dynamic: " + ( end - start ) + " ms" );

            // Do something with r to keep compiler happy
            System.out.println( r );

        }

    }
	
	private int addDynamic( int a, int b ){
		
		return a+b;
	}
	
	private static int addStatic( int a, int b ){
		
		return a+b;
	}
	
}

Solution 9 - Java

The methods you can declare as static are the ones that don't require instantiation, such as

public class MyClass
{
    public static string InvertText(string text)
    {
        return text.Invert();
    }
}

Which you can then in return call out in any other class without instanciating that class.

public class MyClassTwo
{
    public void DoSomething()
    {
        var text = "hello world";
        Console.Write(MyClass.InvertText(text));
    }
}

... But that's something you probably already know. It doesn't give you any real benefits per se, other than making it more clear that the method doesn't use any instance variables.

In other words, you can most safely just turn it off completely. If you know you will never use a method in other classes (in which case it should just be private), you don't need it to be static at all.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlundellView Question on Stackoverflow
Solution 1 - JavaSamuel RossilleView Answer on Stackoverflow
Solution 2 - JavaJackView Answer on Stackoverflow
Solution 3 - JavaIstvan DevaiView Answer on Stackoverflow
Solution 4 - JavaFooFView Answer on Stackoverflow
Solution 5 - JavaBlackView Answer on Stackoverflow
Solution 6 - JavaBlundellView Answer on Stackoverflow
Solution 7 - JavaEdwin DalorzoView Answer on Stackoverflow
Solution 8 - JavaScheintodView Answer on Stackoverflow
Solution 9 - JavaNeroSView Answer on Stackoverflow