Russ Wheeler
Russ Wheeler

Reputation: 2630

Android performance issues with large Hashmap

I am writing a simple word game using a Java gaming library called LibGDX.

I have a dictionary of 370k words in txt file that takes up about 4mb.

In my game, i read the words in using the following code

wordsScored = new HashMap<>();
    double start = System.currentTimeMillis() % 100000;
    Gdx.app.error("1","start "+ start);

    FileHandle handle = Gdx.files.internal("words.txt");
    String allWordsString = handle.readString();
    String wordsArray[] = allWordsString.split("\\r?\\n");

    for (int i = 0; i < wordsArray.length; i++) {
        String word = wordsArray[i];
        wordsScored.put(word, scoreWord(word, getGameCards()));
        if(i % 10000 == 0) {
            Gdx.app.error("1","i="+i+" - "+ System.currentTimeMillis() % 100000);
        }
    }
    wordsArray = null;

    double end = System.currentTimeMillis() % 100000;
    Gdx.app.error("1","end "+ end);
    Gdx.app.error("1","total "+ (end-start));

When i run this on desktop (you can build on desktop for dev purposes) it takes about 1.5 secs to populate the Hashmap with key and score of word. On Android it takes about 2.5s.

However, after playing on Android 3-4 times, and making no code changes, it suddenly slows right down taking 30-40s!

I'm convinced i have some sort of memory leak, CV or Android is doing something crazy like keeping the Hashmap around like it does with statics.

I tried to use the new Android studio profiler, but that just virtually crashed my machine, and got stuck in a loop whilst everything else on my machine slowed down including mouse etc.

Does anyone know how i can test for this "leak" ? If Android has any issue with letting resources, data from one game to the next? If a Hashmap is a poor data structure for this?

Upvotes: 0

Views: 207

Answers (1)

Stephen C
Stephen C

Reputation: 718926

The code in your question does not have any memory leaks that I can see. If your application does have a leak, then it is somewhere else in your app's code. (For example, it might be keeping references to multiple HashMap objects created by the code. You have not shown us the context in which wordsScored is declared, or explained its lifetime.)

I will grant you that running the code multiple times will generate a lot of garbage, and the issue might be to do with GC performance. But I think it is more likely that there is a memory leak somewhere else in your code (and not Android ...).


I thought there might be a "resource leak" due to this line:

    FileHandle handle = Gdx.files.internal("words.txt");

However, the GDX library doesn't seem to provide any way to "close" a FileHandle, so presumably it is not necessary to do that.

Upvotes: 1

Related Questions