Static vs. dynamic memory allocation - lots of constant objects, only small part of them used at runtime
Posted
by
k29
on Programmers
See other posts from Programmers
or by k29
Published on 2013-06-28T23:09:29Z
Indexed on
2013/06/29
4:28 UTC
Read the original article
Hit count: 161
Here are two options:
Option 1:
enum QuizCategory {
CATEGORY_1(new MyCollection<Question>()
.add(Question.QUESTION_A)
.add(Question.QUESTION_B)
.add...),
CATEGORY_2(new MyCollection<Question>()
.add(Question.QUESTION_B)
.add(Question.QUESTION_C)
.add...),
...
;
public MyCollection<Question> collection;
private QuizCategory(MyCollection<Question> collection) {
this.collection = collection;
}
public Question getRandom() {
return collection.getRandomQuestion();
}
}
Option 2:
enum QuizCategory2 {
CATEGORY_1 {
@Override
protected MyCollection<Question> populateWithQuestions() {
return new MyCollection<Question>()
.add(Question.QUESTION_A)
.add(Question.QUESTION_B)
.add...;
}
},
CATEGORY_2 {
@Override
protected MyCollection<Question> populateWithQuestions() {
return new MyCollection<Question>()
.add(Question.QUESTION_B)
.add(Question.QUESTION_C)
.add...;
}
};
public Question getRandom() {
MyCollection<Question> collection = populateWithQuestions();
return collection.getRandomQuestion();
}
protected abstract MyCollection<Question> populateWithQuestions();
}
There will be around 1000 categories, each containing 10 - 300 questions (100 on average). At runtime typically only 10 categories and 30 questions will be used. Each question is itself an enum constant (with its fields and methods).
I'm trying to decide between those two options in the mobile application context. I haven't done any measurements since I have yet to write the questions and would like to gather more information before committing to one or another option. As far as I understand:
(a) Option 1 will perform better since there will be no need to populate the collection and then garbage-collect the questions; (b) Option 1 will require extra memory: 1000 categories x 100 questions x 4 bytes for each reference = 400 Kb, which is not significant.
So I'm leaning to Option 1, but just wondered if I'm correct in my assumptions and not missing something important? Perhaps someone has faced a similar dilemma? Or perhaps it doesn't actually matter that much?
© Programmers or respective owner