0

I'm developing an app in Android. I use a lot "final static" variables to define my constants. But I'm very stric with the memory used by my application.

Maybe I have 200 constants (int, string, double, ...). It is much better to program with constant variables that use numbers. But, how efficient is this?

Using C I can use #define, and when I put:

#define constant 10
int var2 = constant;
int var3 = constant;

The compiler translates the code to:

int var2 = 10;
int var3 = 10;

But using Java, I think that all these variables stay in memory. There is something so efficient as #define for java?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
jlmg5564
  • 1,380
  • 13
  • 28
  • 3
    http://developer.android.com/training/articles/perf-tips.html. check the link. – Raghunandan May 20 '13 at 12:50
  • 3
    Specifically http://developer.android.com/training/articles/perf-tips.html#UseFinal – Matt Ball May 20 '13 at 12:51
  • final static it's way to create a constant in java – Blackbelt May 20 '13 at 12:51
  • *"But using Java, I think that all these variables stay in memory"* ... and that's different from your C example, how? I don't think you quite understand what the preprocessor macro is doing. – Brian Roach May 20 '13 at 12:52
  • http://stackoverflow.com/questions/3835283/performance-differences-between-static-and-non-static-final-primitive-fields-in And http://stackoverflow.com/questions/1496629/do-static-members-help-memory-efficiency – Anas EL HAJJAJI May 20 '13 at 12:52
  • I think the compiler makes the sustitution, anyway 200 integers/doubles is not something to be worried about. Do not try to hiper-optimize, it is not worth it (somebody said that premature optimization is the mother of 90% of all evils, or something like that...) – SJuan76 May 20 '13 at 12:52
  • There's a reason the people from whom you copy and pasted this posted it as a comment rather than an answer. – Brian Roach May 20 '13 at 12:57

1 Answers1

3

If you want to use something similar to C's ifdef you should do something like:

final static boolean COMPILE_THIS = false;

This will cause the following code not to be part of your program ("compiled"):

if (COMPILE_THIS) {
   printToScreen("HELLO");
}

Google uses this technique a lot in the Android code when they don't want to "compile" parts of it.

EyalBellisha
  • 1,874
  • 19
  • 28