I am wondering about the performance of Java HashMap vs JSONObject.
It seems JSONObject stores data internally using HashMap. But JSONObject might have additional overhead compared to HashMap.
Does any one know about the performance of Java JSONObject compared to HashMap?
Thanks!
A JSONObject is an unordered collection of name/value pairs whereas Map is an object that maps keys to values. A Map cannot contain duplicate keys and each key can map to at most one value. We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format.
JSON is a text based object that different from HashMap.
JSONObject is "native" to Android SDK, JsonObject is probably the one from Gson library, the one that I use. Two different package, don't work with both ;) choose one. I had some issue with the date formatting in JSONObject.
A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the put and toString methods.
As you said, JSONObject
is backed by a HashMap
.
Because of this, performance will be almost identical. JSONObject.get()
adds a null check, and will throw an exception if a key isn't found. JSONObject.put()
just calls map.put()
.
So, there is almost no overhead. If you are dealing with JSON objects, you should always use JSONObject
over HashMap
.
I would say the question doesn't make sense for a few reasons:
Existing answers are correct, performance differences between the two are negligible.
Both are basically rather inefficient methods of storing and manipulating data. More efficient method is typically to bind into regular Java objects, which use less memory and are faster to access. Many developers use org.json's simple (primitive) library because it is well-known, but it is possible the least convenient and efficient alternative available. Choices like Jackson and Gson are big improvements so it is worth considering using them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With