0

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?
4

2 回答 2

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

    It depends. If you don't initialize them explicitly, they will assume their default values (null for objects). Does this make sense for your particular application? Or does do it make sense to have initialized objects with defaults values for their members?

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

    When you allocate objects, they will occupy space on the heap. Too many allocations will slow down your app. So yeah, it will affect performance if you have a huge number of objects so it depends on how many objects your app will be allocating.

于 2013-10-07T10:36:54.760 回答
1

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.

于 2013-10-07T10:45:58.067 回答