JSON VS simple string manipulation to parse HttpRequest in Android
I face the common case of having to extract some information in a remote server via an HttpPost request. Imagine we are in the case of a weather app retrieving some weather info.
The server send a 开发者_JAVA百科long inputstream and we are interested in extracting some information from this stream. Keep in mind we are in a memory-cpu bound environment.
We have two options:
1) We use a JSON or XML parser to extract the informations.
This is the recommended method, but it has some disadvantages:
It is painfully verbose, especially if we want little information from a big stream.
It should be faster and more garbage collection-friendly, but I'm not sure this is the case for the aforementioned case (little information from a big stream).
2) We use simple string manipulation (SSM):
We reduce the dimension of the inputstream by grossly trimming off useless infos, and then we extract the informations from a compact string. For this purpose, we can build filters using static methods, to reduce the work of the garbage collector.
Also this method has some disadvantages:
- I think this method is strongly discouraged
- The more informations we extract, the slower this method is. I think there is a critical point in the performance curve where SSM becomes slower.
- It might be less flexible than JSON or other stock parser.
But also some important advantages:
- Concise, human-readable code.
- It might be difficult to modify an existing filter, but it is much easier to create a new one.
To sum up, the question is:
1) Is simple string manipulation a big no-no approach, or it is reasonable to consider its use? 2) If you answered yes (big no-no approach) to the previous question, could you explain your reason?
cheers :)
I would request the information in JSON format (not XML which is more verbose with no advantage) and use an event-based parser to locate the data wanted by processing the stream in line as it's read from the server.
That will be very easy on memory, and require no change in what the server delivers. It will also be far more reliable and resistant to changes than any home-grown string slicing solution you might put together.
I have a freely distributed very light-weight pull parser for JSON on my website. Others are available from http://www.json.org.
I second the suggestion of using JSON. A parser I've made good experience with is Jackson. It offers both POJO as well as STAX-API for low memory consumption.
精彩评论