Carlos Bribiescas
Carlos Bribiescas

Reputation: 4407

Is initializing a boolean to false or true more efficient?

In java if you do not initiate a boolean it defaults to false. So if i say

boolean myFavoriteBoolean = true;

Is this more work than

boolean myFavoriteBoolean = false;

My thinking is that in the first example it starts false and has to be set to true or is that not the case? Also, I know this is a moot point from a performance perspective, but I'm asking because I'm interested if I understand how Java is working under the hood.

Upvotes: 0

Views: 2045

Answers (4)

Steve Kuo
Steve Kuo

Reputation: 63094

boolean fields default to false at the JVM level. Initializing to true results 3 extra bytecode instructions.

public class BoolTest {
  public boolean foo;
}

compiles to

0:  aload_0
1:  invokespecial   #1; //Method java/lang/Object."<init>":()V
4:  return

Compare to initializing to true

public class BoolTest {
  public boolean foo = true;
}

compiles to

0:  aload_0
1:  invokespecial   #1; //Method java/lang/Object."<init>":()V
4:  aload_0
5:  iconst_1
6:  putfield    #2; //Field foo:Z
9:  return

Upvotes: 1

Stephen C
Stephen C

Reputation: 718788

If the variable is an instance variable or a static variable, then the variable is default initialized to false, and there is a good chance that the JIT compiler can make use of this and optimize away an explicit initialization to false. (In practice, heap memory is zeroed by the garbage collection / heap manager, and this happens irrespective of how the memory is going to be used.)

If the variable is a local variable, then there is no default initialization, and (typically) there is no automatic zeroing of stack frames that the JIT compiler can depend on. Thus, you would expect initialization to false or true to take the same time.


However, this "smells" of premature optimization. The actual difference is likely to be one or two native code instructions once the code is JIT compiled. The chances are that it will make no significant difference to your application. Furthermore, changing your program to exploit the (hypothetical) difference in performance will most likely make your code less readable, and have "knock on" consequences for the performance of other parts of your program.

Best practice is to only contemplate this kind of micro-optimization if:

  • you have clear evidence that optimization is required; i.e. your application does run too slowly for representative benchmarks, and

  • you have clear evidence that the code where the variable is declared and initialized is actually a performance bottlneck; i.e. the profiler tells you this.

Upvotes: 1

Joop Eggen
Joop Eggen

Reputation: 109547

If talking about fields, where there are default values: a created object is zeroed, so only setting it to true would need one more instruction - one would think.

However there is a idiotic case, demonstrating the difference between initialisation and default initialisation:

    class A {
        A() {
            b();
        }

        void b() {
        }
    }

    class B extends A {
        boolean c = false;
        boolean c2;

        @Override
        void b() {
            c = true;
            c2 = true;
        }

        B() {
            super();
            System.out.printf("%s %s%n", c, c2);
        }
    }

new B();

This will yield

false true

The reason: after the call to super() (or at the beginning of the constructor if no super), all field initialisations happen: at that point c was set to true, but is now iniitialized to false.

This is defined behaviour, and a reason never to call overridable functions in the constructor.

Mind also that in the first B.b() all fields of B still had their default value.

So:

  • No initialisation is most efficient
  • Any initialisation costs the same
  • There is a difference between no initialisation and initialisation with default for idiotic code

I once removed an initialisation = null (cleaning up legacy code) causing an error.

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279950

Assuming you are referring to an instance field of type boolean, then the answer is in the JLS chapter regarding instance creation expressions.

The new object contains new instances of all the fields declared in the specified class type and all its superclasses. As each new field instance is created, it is initialized to its default value (§4.12.5).

[...]

Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type. This process can be directed by explicit constructor invocation statements (§8.8) and is specified in detail in §12.5.

After all the super constructor calls

Execute the instance initializers and instance variable initializers for this class, assigning the values of instance variable initializers to the corresponding instance variables, in the left-to-right order in which they appear textually in the source code for the class. [...]

So

boolean val = false;
//and
boolean val = true;

behave the exact same way.

Upvotes: 3

Related Questions