Should I parse JSON once and store the data in an ArrayList for future use OR parse it every time I need the data?

Viewed 116

I have a JSON Array that contains JSON Objects. Each JSON Object only has a simple key/value pairs (no nested array or something like that). For example:

[
  {
    "id": "01",
    "name": "Zero One",
    "desc": "Something about Zero One"
    ...
  },
  ...
]

Values in those JSON Objects will be used later by the app.
Based on my limited experience, there are two easy ways to accomplish this:

  1. Parse the JSON ONCE at app startup and store ALL the objects in an ArrayList (or any List or even a Map) of POJOs.
    My worry about using this method is memory usage and a relatively long waiting time. For example, if the JSON Array contains hundreds or even thousands of JSON objects, that means the app has to allocate hundreds/thousands of POJOs worth of memory, and I don't know how much or how I can calculate it exactly. Ideally, a HashMap or ArrayMap is probably better for getting/accessing the value, but I read that Map is even more memory hogging than a simple List.
  2. Parse the JSON only when the data is needed.
    My worry about this method is maybe performance. I said "maybe" because I don't know exactly how taxing parsing a JSON file/string is. If I have to parse the JSON every time the app asks for it, then I essentially have to do a loop through the JSON Array, get the JSON Object, and check for a matching id, to get the value.

Which one is better in terms of performance AND memory efficiency?
Is there an alternative that's even better than both?

1 Answers

Processing the entire JSON file by loading it into memory can be painful and can crash a lot memory constrained devices. However, using the a Jackson JSON parsing library (https://github.com/FasterXML/jackson) you can stream the http-request as a Reader into Jacksons Streaming API which will allow you to process each JSON object as soon as it comes down from the pipe. This allows you to process the data as it comes down the pipe instead of loading the entire JSON file.

I use the ObjectMapper from Jackson to deserialize the JSON into a POJO. This allows me to work with domain objects throughout my app, therefore, I don’t have to worry about parsing JSON objects all over the place (or cursors if you move the data into a DB locally on the device). If you were to load the entire JSON file into the object mapper you’d create a humongous object graph which may ballon your memory out of the bounds of what’s available and you might get a OutOfMemoryException. The end goal is to process EACH of the JSON objects as they come down, but also have the benefit of using a POJO to do so.

Related