使用Json时如何避免垃圾回收?

时间:2015-10-14 15:32:14

标签: libgdx

我目前正在使用Json课程加载我的关卡。问题是,应用程序滞后于开头,这可能是由于GarbageCollector删除了所有未使用的JsonValue对象。我目前不知道,如何解决这个问题,任何建议都会受到赞赏,

带有json东西的WorldLoader类,代码看起来很多,但非常直接:

package com.Sidescroll.game.Helpers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.Sidescroll.game.GameObjects.Background;
import com.Sidescroll.game.GameObjects.Platform;
import com.Sidescroll.game.GameObjects.Player;
import com.Sidescroll.game.GameWorld.GameWorld;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;

public final class WorldLoader {

    private WorldLoader() {}

    public static HashMap<String, GameWorld> worlds = new HashMap<String, GameWorld>();

    private static JsonValue jsonPlatforms, jsonSpawn, jsonBackgrounds;

    public static GameWorld loadWorld(String levelName) {
        if(worlds.get(levelName) != null) return worlds.get(levelName);

        //load json file
        FileHandle handle = Gdx.files.internal("levels/" + levelName + ".json");
        String fileContent = handle.readString();
        JsonValue json = new JsonReader().parse(fileContent);

        jsonPlatforms = json.get("platforms");
        jsonBackgrounds = json.get("backgrounds");
        jsonSpawn = json.get("spawn");

        //loads platforms
        List<Platform> platforms = new ArrayList<Platform>();
        for(JsonValue pValue : jsonPlatforms.iterator()) {
            Platform platform = new Platform(pValue.getInt("x"),
                                    pValue.getInt("y"),
                                    pValue.getInt("width"),
                                    pValue.getInt("height"),
                                    Platform.Type.valueOf(Platform.Type.class, pValue.getString("type")),
                                    pValue.getString("variant"));
            platforms.add(platform);
        }

        //create player
        Vector2 vecSpawn = new Vector2(jsonSpawn.getInt("x"), jsonSpawn.getInt("y"));
        Player player = new Player(vecSpawn, platforms);

        //loads backgrounds
        List<Background> backgrounds = new ArrayList<Background>();
        for(JsonValue bgValue : jsonBackgrounds.iterator()) {
            Background bg = new Background("bin/sprites/" + bgValue.getString("name") + ".png",
                                            bgValue.getInt("x"),
                                            bgValue.getInt("y"),
                                            bgValue.getInt("width"),
                                            bgValue.getInt("height"),
                                            bgValue.getBoolean("front"));
            backgrounds.add(bg);
        }

        worlds.put(levelName, new GameWorld(player, platforms, backgrounds));
        return worlds.get(levelName);
    }
}

0 个答案:

没有答案