Java HashMap vs JSONObject

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:

  1. Comparing apples to oranges: HashMap and JSONObject are intended for 2 completely different purposes. It's like asking "is the Person class or Company class more efficient for storing a PhoneNumber object". Use what makes sense.
  2. If you are converting to/from JSON, you are likely sending the data to a far away place (like a user's browser). The time taken to send this data over the network and evaluate it in the user's browser will (likely) far eclipse any performance differences of populating a Hashmap or JSONObject.
  3. There is more than 1 "JSONObject" implementation floating around out there.
  4. Finally, you haven't asked about what sort of performance you would like to measure. What are you actually planning to do with these classes?

Tags:

Java

Json

Hashmap