5

why on all demos and tutorials in SQLiteOpenHelper class variables are always: public static final

Have a look:

    public static final String ORDER_ID = "order_id";
    public static final String ORDER_LOGIN_NAME = "login_name";
    public static final String ORDER_RESTO_U_NAME = "resto_uniqe_name";

My question is: I am making an application and its database is too big. So, I will have to make atleast 60-70 variables of these kind. Won't it affect application performance? As these are static variables.

Any help will be highly appreciated....

pioneerBhawna
  • 578
  • 7
  • 15
  • By "affect application performance" do you mean use too much memory, or taking too long to process? – Marcelo Mar 21 '14 at 09:35
  • I do think he is wondering if using static final won't be heavier than using the String in the classic way. – bottus Mar 21 '14 at 09:37
  • 1
    Check out the "TEST 4: VARIABLE VS CONSTANT" in this page: http://www.devahead.com/blog/2011/12/coding-for-performance-and-avoiding-garbage-collection-in-android/ It is not slow as you think. This official guide is also a good reference: http://developer.android.com/training/articles/perf-tips.html#PreferStatic – Siu Mar 21 '14 at 09:38
  • I am concerned about the memory space. – pioneerBhawna Mar 21 '14 at 09:41

1 Answers1

4

Well, whether they public or private or package-protected depends on your needs, but final static is a good way of declaring constants per Android guidelines, take a look here for explanation: http://developer.android.com/training/articles/perf-tips.html#UseFinal

Consider the following declaration at the top of a class:

static int intVal = 42;
static String strVal = "Hello, world!";

The compiler generates a class initializer method, called , that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups.

We can improve matters with the "final" keyword:

static final int intVal = 42;
static final String strVal = "Hello, world!";

The class no longer requires a method, because the constants go into static field initializers in the dex file. Code that refers to intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string constant" instruction instead of a field lookup.

nikis
  • 11,166
  • 2
  • 35
  • 45