Sparsearray vs Hashmap what’s the difference?

Asked

Viewed 88 times

4

I was doing my daily refactoring and came across a warning.

use new Sparsearray(...) to Instead for Better performance

Okay, but what’s the difference between Map and SparseArray?

This is my code:

private Map<Integer,Drawable> mapTooth = new HashMap<>();
  • 1

    I suggest that reading

  • Thanks @nullptr, if you could have talked and sent the link would be even better. After all, I think someone new, who still doesn’t understand English, may need to thank you anyway.

1 answer

5


It is an optimization of HashMap. Java works with everything based on reference types that generate allocation, and portando occupy more memory and pressure ni Garbage Collector. Still bad for the fact that not all objects are derived from Object, as it is in C#, for example, there are so-called primitive types to give performance (soon you will have ways to create types by value, which shows that language was born crooked believing in the fallacy that object orientation would solve all evils). It doesn’t help the fact that Generics of language being a patch that was made later. So to get gains when you’re going to use primitive types on a map, a specific structure was created to deal with this more optimally.

While reducing allocation the implementation may not be so good, I do not guarantee that it is always advantageous.

The bad part is that there are variations of it since it can not use Generics. So SparceArray it would actually be the same as HashMap<int, Object> if you could do it like this. And if you want to use a int as value, it would be the case to use SparseIntArray. If you want the key to be one long would be something like LongSparseArray. Imagine that it is almost impossible to create all variations.

The SparceArray can use Generics the type of the value, provided that it is by reference.

As far as I know is not part of the standard Java library so the code is not portable. A nice gambit to circumvent language limitation. And the warning seems hasty, it’s not necessarily faster. If you are not sure that this will improve your code think well before doing, test (have to know how to test) and see if it paid off.

  • So "Sparsearray" is only recommended for Primitive types and Hashmap when using Object is this in a more grotesque way ? Or am I totally wrong ?

  • The first part yes, and only for some three primitives, the second, no, is for all types inherited from Object.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.