Gita
Gita

Reputation: 58

Is there any advantage of using Value Object over Map in java

I have to store a product and its corresponding price. Which of the below methods would be better:

Method 1:

public class Product {

    String productName;

    Integer productCost;

}

Method 2:

Map<String, Integer> product.

I assumed that using Map make things easier but still I was suggested to use value Object.

Is there any advantage of using Method 1 over Method 2 in terms of memory and performance? In what situation we can use these two methods?

Upvotes: 0

Views: 243

Answers (2)

arshajii
arshajii

Reputation: 129477

You should consider using a Map if you need to quickly look up the price of an item based on its name. The difference here is that this lookup operation would be O(n) if you choose the first method and O(1) if you choose the second (since with the first you have to go through your entire collection of Products to find the one with the right name).

If you don't have too many products you want to store (e.g. ~10, as you mentioned), then the performance difference will probably be negligible, and you might be better off choosing whichever approach is easier to understand/manage. As the number of products you want to store increases substantially, then the difference can become more apparent.

Of course, if you don't need this quick look up feature then it doesn't make much sense to use a Map at all.

Upvotes: 1

arjacsoh
arjacsoh

Reputation: 9232

The value in the Object is recommended way when you want to keep the software quality high. With the Map you should "carry" it whenever you need to use the value of the Object and consequently you create a lot of copies of it. Getting the value from a Map has an impact on performace as well and you have moreover to save all the Objects created in it, preventing the garbage collector to sweap them when no more needed.

Upvotes: 1

Related Questions