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?

7

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.