3

I've been reading about performance tips on the Android Developers site, and one of the recommendations is to use static final for constants. The example illustrates the use of static final for an int and a string declarations. The explanation is clear on why static final is faster when declaring an int. However, for the string example it merely states that code which refers to this string will use the "relatively inexpensive string constant instruction".

I tried to look up how this instruction is performed at runtime and why it is less expensive, but couldn't find anything. Can anyone elaborate on the string constant operation?

M.S
  • 1,580
  • 1
  • 13
  • 22

3 Answers3

3

The example given declares two constants:

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

Because of the final keyword, the class doesn't need a <clinit> method anymore. Moreover, the int value is used as is at the place where you use this constant. there is no field lookup to find the intVal field of the object, but instead the value 42 is used everywhere.

This same advantage applies to strings too. Instead of having to lookup the field in the class, the code using the constant can just use a precompiled reference to the location of the string.

And this makes other optimizations possible too. For instance, the length of the string is also known at compile time, so it may be optimized away and replaced by its outcome.

GolezTrol
  • 114,394
  • 18
  • 182
  • 210
  • Can you please explain what is a precompiled reference to the location of the string? – M.S Dec 29 '15 at 23:11
  • The strings in your program are compiled into a string table. This is basically a large buffer of string data. Because these strings are constant, the compiler already knows which string is at what address in the string table. So looking up this string can for the largest part be done at compile time already. I'm trying to find a good reference of this, although I already found a [related question](http://stackoverflow.com/questions/15067222/where-to-store-global-constants-in-an-android-application). – GolezTrol Dec 29 '15 at 23:18
2

Many operations on constant strings can be done at compile time. Say, str.length() can be replaced with actual number at compile time if str is declared static final.

Rediska
  • 1,392
  • 10
  • 14
-1

I think it's because you don't have to mention about other object properties. Because the static final String strVal property refers to all different objects. That's why it is less expensive.

To clarify I will give you an example:

public class House {
    public static int doors;
}

House a.doors = 3;
House b = new House();
System.out.println("b has : "b.doors); //prints b has 3 doors

So when variable a has 3 doors. Then all other objects will also have 3 doors. So that's the reason why I think it's less expensive.

superkytoz
  • 1,267
  • 4
  • 23
  • 43