13

Suppose in an apk we have 1000 strings in strings.xml.

So when we run this app on device at that time all the strings are always available in heap memory. Or they loaded in memory when we call getString() method of Context to load the Strings.

Are all strings in the heap during runtime?

Nachi
  • 4,218
  • 2
  • 37
  • 58
Sharad
  • 589
  • 5
  • 19
  • 2
    android compile generate R file, this file contain string ids, they are all java constant. Read the AssetManager and StringBlock souce code may help u – shuabing Oct 25 '16 at 08:34
  • Possible duplicate of [In Android, is there a reason to use string resources for strings that are not going to be translated?](http://stackoverflow.com/questions/32587336/in-android-is-there-a-reason-to-use-string-resources-for-strings-that-are-not-g) – AZ_ Oct 26 '16 at 08:29
  • http://stackoverflow.com/a/16433112/185022 – AZ_ Oct 26 '16 at 08:33
  • http://stackoverflow.com/questions/21308623/xml-string-resources-vs-java-constant-strings – AZ_ Oct 26 '16 at 08:34
  • 1
    Those links don't solve my problem. My only concern is whether all strings are in heap at a time? – Sharad Oct 27 '16 at 08:46
  • They are called by their ids,similar to a button with no functions on a layout.Probably are in a heap at a time – Fay Zan Oct 27 '16 at 09:24
  • 1
    I just don't understand those people who just keep pasting links rather than reading the question. – Kimi Chiu Nov 14 '18 at 15:11

1 Answers1

12

This is a great question. We can try to find the answer by studying the Android source code.

All calls to getString() get routed to the following method inside android.content.res.AssetManager:

/**
 * Retrieve the string value associated with a particular resource
 * identifier for the current configuration / skin.
 */
/*package*/ final CharSequence getResourceText(int ident) {
    synchronized (this) {
        TypedValue tmpValue = mValue;
        int block = loadResourceValue(ident, (short) 0, tmpValue, true);
        if (block >= 0) {
            if (tmpValue.type == TypedValue.TYPE_STRING) {
                return mStringBlocks[block].get(tmpValue.data);
            }
            return tmpValue.coerceToString();
        }
    }
    return null;
}

loadResourceValue is a native function and can be found in android_util_AssetManager.cpp

The native method calls getResource() inside the class ResTable here.

The constructor for ResTable calls addInternal() here which reads the resources for each package id in the app. This table is later used to perform lookups of resources.

So to answer your question, yes, all strings (and indeed all resources) are parsed from the filesystem and loaded into a lookup table in the native heap.

Nachi
  • 4,218
  • 2
  • 37
  • 58