解析〜1 MB JSON在Android上速度很慢 [英] Parse ~1 MB JSON on Android very slow

查看:1182
本文介绍了解析〜1 MB JSON在Android上速度很慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保存在我的资产文件夹中的大约1MB JSON文件,我需要在我的应用程序在每次运行时加载。我发现,内置JSON解析器(org.json)解析文件很慢,但一旦它的解析,我可以访问并很快操纵数据。我的那一刻起我点击应用程序的活动1中长大的那一刻算出来的多达7或8秒,但短短几毫秒,从活动1到活性2依赖于从加载的数据处理的数据活动1。

I have an approximately 1MB JSON file stored in my assets folder that I need to load in my app every time it runs. I find that the built-in JSON parser (org.json) parses the file very slowly, however once it's parsed, I can access and manipulate the data very quickly. I've counted out as many as 7 or 8 seconds from the moment I click on the app to the moment the Activity1 is brought up, but just a few milliseconds to go from Activity1 to Activity2 which depends on data processed from the data loaded in Activity1.

我把文件读入内存,并使用解析它:

I'm reading the file into memory and parsing it using:

String jsonString = readFileToMemory(myFilename)
JSONArray array = new JSONArray(jsonString);

在这里readFileToMemory(字符串)看起来是这样的:

where readFileToMemory(String) looks like this:

private String readFileToMemory(String filename) {
    StringBuilder data = new StringBuilder();       
    BufferedReader reader = null;
    try {
        InputStream stream = myContext.getAssets().open(filename);
        reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        int result = 0;
        do
        {
            char[] chunk = new char[512];
            result = reader.read(chunk);
            data.append(chunk);
        }
        while(result != -1);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data.toString();
}

有没有人要我怎么可以加快数据的初始加载和分析有什么建议?我或许应该掩盖加载屏幕背后的整个过程?

Does anyone have any suggestions to how I can speed up the initial loading and parsing of the data? Should I perhaps mask the whole process behind a loading screen?

推荐答案

的JSONObject - 从json.org之一,是使用JSON解析最简单的API。然而,它是有代价的 - 服务表现。我已经做了与JSONObject的,GSON和杰克逊广泛的实验。看来不管你做什么,JSONObject的(因此JSONArray),其中将是最慢的。请切换到杰克逊或GSON。

JSONObject -- the one from json.org, is the simplest API to use to parse JSON. However it comes with a cost -- performace. I have done extensive experiments with JSONObject, Gson and Jackson. It seems no matter what you do, JSONObject (and hence JSONArray) will be the slowest. Please switch to Jackson or Gson.

下面是两个相对表现

(最快)的 杰克逊> GSON>> JSONObject的 (最慢)

(fastest) Jackson > Gson >> JSONObject (slowest)

请参阅:结果
  - 杰克逊结果
  - GSON

这篇关于解析〜1 MB JSON在Android上速度很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆