Search code examples
javaandroidperformancememory-managementstatic-variables

is it a good practice to declare static variables globally as null?


I'm just confused and trying to figure out if is a good idea

  • To have static variables declared as null globally in a class that can be accessed by all the other classes?
  • Can this affect the performance of the application as a whole either in a good way or bad way?

Solution

  • To have static variables declared as null globally in a class that can be accessed by all the other classes?

    When are you thinking it's appropriate to initialize that null global variable? You can declare it to point to something, use a static block, or create a singleton-like method to initialize the reference on first use. That's it.

    Google thinks that global static variables are a bad idea. Should you have them at all? Maybe you should think about that instead of when to initialize them.

    Can this affect the performance of the application as a whole either in a good way or bad way?

    It's unlikely to matter, unless initialization takes too long for your requirements. You should never assume one way or the other that you know what will affect performance. Write code and profile it under meaningful conditions to know what's important.