-2

My application requires about 50,000 different strings. I could store them in a database, but I was wondering if it is possible and advisable to store them as string resources.

  • Is it a good approach to store lots of string in string.xml file?

  • How many string we can store in string.xml file ?

  • Searching Cost of string by name ? like

Code Snippet:

private String getStringResourceByName(String aString) {
    String packageName = getPackageName();
    int resId = getResources().getIdentifier(aString, "string", packageName);
    return getString(resId);
}

Are there any other approach that i can use?

K Guru
  • 1,292
  • 2
  • 17
  • 36

1 Answers1

2

Is a bit hard to frame this answer but let me try:

How many string we can store in string.xml file ?

First at all, resources id are compiled as constants in R class. That said, in Limitations of the Java Virtual Machine say:

The per-class or per-interface constant pool is limited to 65535 entries by the 16-bit constant_pool_count field of the ClassFile structure (§4.1). This acts as an internal limit on the total complexity of a single class or interface.

So, 50k string resources seems possible. As skeptic, after a bit of experimenting, it seems that you can have up ~33k string resources in a new blank project. Beyond this limit, it produces a compile-time error "too many constants".

Searching Cost of string by name ?

In linked project I did basic comparision between getResources().getIdentifier(..); (by name) and getResources().getString(id); (by id).

Get by id is 13x faster than get by name.

I've also compared it with SQLite. getResources().getIdentifier(..); is 1.5x faster than SELECT * FROM table WHERE name = 'string_x'

Is it a good approach to store lots of string in string.xml file ?

IMHO, no.

Pros:

  1. GetResurceByName it's just 1.5x faster than SQLite.

Cons:

  1. Increase compile time significantly.
  2. Guaranteed that at some point you will receive 'too many constants'.
  3. It's hard to localize. The 2^16 limit involves all translations.

Another Approach?

This post could help you to ship the application with a pre populated database with your app: Ship an application with a database

Community
  • 1
  • 1
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95