Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a "string constant" operation in Android?

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?

like image 582
M.S Avatar asked Dec 13 '25 13:12

M.S


1 Answers

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.

like image 166
GolezTrol Avatar answered Dec 15 '25 05:12

GolezTrol