0

Is it ok, if I mark all fields static in Activity? Does it improve performance? I mean, Activity is created just once and there is no need for many instances. Here is an example:

private static Spinner mNtries;
private static Spinner mTies;
private static Spinner mTions;
private static Button mTButton;
private static Button mDButton;

Or is it not good practice?

Marian Paździoch
  • 8,813
  • 10
  • 58
  • 103
Bobans
  • 439
  • 6
  • 13
  • is your app slow right now? let android handle creation and destruction of widgets. i.e don't mark them as static – vikki Mar 07 '13 at 09:15

2 Answers2

1

The question is, why would you want static fields? I think you should avoid static stuff as much as possible. If you use static then you may have memory leaks.

It looks like you want to use Views as the static, and good practice says you should only use them as non-static because there really are no scenarios where you need them static.

Simon Zettervall
  • 1,764
  • 1
  • 15
  • 31
  • 1
    Why should not we use static fields? Sorry, but your answer is little ambiguous. How could we have _memory leaks_ if all those objects necessary during whole application lifecycle? – bsiamionau Mar 07 '13 at 19:29
  • @zvzdhk I do not see the point in having static fields, it is a bad design flaw to rely on it, the same functionality could be used using scope variables instead. It may be a memory leak because static stuff does not get garbage collected. – Simon Zettervall Mar 08 '13 at 10:49
  • At first, there is no any reason to collect this stuff. At second, GC actually _collects_ static stuff. – bsiamionau Mar 08 '13 at 13:00
  • @zvzdhk Do you mean it is not needed to collect static objects? Yes, GC does actually collect it but only when the class containing the static stuff has been unloaded and in normal circumstances you should not consider unload a class. – Simon Zettervall Mar 08 '13 at 13:54
  • @zvzdhk check this out: http://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil – Simon Zettervall Mar 08 '13 at 13:55
  • I mean that in this application you need not to to unload activity class during all application life cycle. – bsiamionau Mar 08 '13 at 13:56
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25846/discussion-between-zvzdhk-and-simon-zettervall) – bsiamionau Mar 08 '13 at 13:56
1

Big No Your static fields inside activity does not improve performance,Once your activity get loaded by class loader all your static fields also loaded, static variable or constant will not be garbage collected.

subodh
  • 6,136
  • 12
  • 51
  • 73
  • There is no any reason to collect activity instance - it is important during all application lifecycle, isn't it? – bsiamionau Mar 07 '13 at 12:27