Reputation: 16398
My app needs three per-defiend arrays to run: an array of Strings and two arrays of integers. Each array has a length of 100. To add these arrays to my app, I thought of the following two approaches:
Utils.java
class as a static final variables and reference them in my activities whenever I needed them.res
folder and construct the array (using getStringArray()) whenever I needed it.Now, I am wondering:
Upvotes: 3
Views: 312
Reputation: 4380
I see it as better practice to have them externally in a file, mainly because you can change them easier without rolling out new code and compability reasons. You can for instance read them in at start-up or just once when needed to a (dynamic) Utils class, to get higher efficiency.
If you need (or want) a quick response from the application I would without a doubt go with the higher efficiency choice (hard-code/load once at start-up) if the strings are relatively small. 200 Integers
and 100 (small) Strings
take up very little space really. A String[100]
of an avarage of 100 characters will take up about 24 kB and the 200 int
s would take up 824 Bytes of memory (including array object overhead).
Upvotes: 1
Reputation: 1019
This is the usual time vs space trade off. I would combine the 2 approaches you mentioned. Load the arrays from a resource file and access them via some predefined getter methods. This allows you to change your approach later on, if time or space becomes am issue which I'm guessing it won't, without touching the code that uses the arrays
Upvotes: 0
Reputation: 23665
If the arrays are the same for every language etc. I'd go with hardcoding in your Utils class. It's surely the fastest way, because if you have them as a resource, your app has to read the file at runtime which is way slower then having it in the code already. The overall size of your app will not change much as with every method, you'll have the data somewhere in your app's package. Be it in code or in a textfile in the resources. Actually, as the hardcoded integers in code are stored binary as integers, they need slightly less memory (every integer in java requires 4 bytes to store, while an integer like 1000000000 in a textfile would require 10 bytes.
Only if those arrays were different for e.g. different languages, you should use the solution with resources.
Upvotes: 2
Reputation: 10677
Store data in text file or properties file. And once there is request to these details read them in Arrays.
And then you can keep it in memory as per your need.
Upvotes: 1