Autoboxing, a little thing, can cause big problems for Android App Performance



To ensure your app performs well across a wide variety of devices, you always try to use best practices. On that front memory optimization is often a demanding task. Most of the time we always think on the bigger side of it and miss the small thing that can add up to a big problem. Autoboxing is a topic that often goes unnoticed when talking about performance issues.

Autoboxing is a great language feature, until you realize how much of your performance is being lost to its convenience. You cannot imagine a simple Autoboxing operations can easily tear through your Application’s memory.


What is Autoboxing?

Till JDK 1.4, when we work with primitive types, it requires repetitive work of converting the primitive types into wrapper classes and vice-versa. Let’s say if we want to create a List with Integers, we have to explicitly wrap them as Integer and we need to unwrap it to get int value.

So since JDK 1.5, Conversion from primitive types to corresponding wrapper objects and vice versa can happen automatically.

Boxing: Conversion of a primitive type to the corresponding reference type (int -> Integer).

Unboxing: Conversion of the reference type to the corresponding primitive type (Integer -> int).


How it causes problem?

As we discussed Java provides corresponding wrapper classes that match primitive types, and act as object wrappers. These classes give the same functionalities as primitives but can be used with generic collections. However their size in memory is not the same. An Integer object occupies 4 times more memory as primitive int.


In the example below, the API call adding a primitive int value but the collection API takes Integer object. This assignment will perform an Autoboxing operation from int to Integer object.

// Here is primitive variable
int value = 5;
                  
List<Integer> list = new ArrayList<>();
//autoboxing to add primitive type (int) in collection class
list.add(value);

For a single call, this may not matter much. However, if we are using it frequently, for example in an inner loop, it might occupy a lot of memory unnecessarily and cause a big memory threat.​

// Here is generic variable
Integer sum = 0;  
for(int i= 0;i< 100;i++){
      // autoboxing to convert int into Integer
       sum = sum + i;
}

As you can see in the above example, 100 new objects allocation along with the sum calculation. But in case of primitive it doesn’t require any additional allocation overhead.

This will also overhead of more garbage collection and decrease the runtime performance. It can be especially painful with data structures like HashMap. Let’s consider another code:

HashMap<Integer, String> map = new HashMap< >();
// Put the value in the map where key is primitive type.
map.put(1, "TestValue"); // expected key is Integer type

// Get the value from the map where key is primitive type.
map.get(1); // expected key is Integer type

In the above code put and get operations will use Autoboxing and cause additional load. Basically anytime you insert, update or retrieve a value with this generic container when a primitive is involved you end up boxing or unboxing values.


How to resolve the problem?

To resolve the problem of autoboxing Android provided custom containers SparseArrays and ArrayMap to use instead of traditional containers like HashMap. These containers are design specifically to fight Autoboxing problem and eliminate both runtime overhead and additional memory allocation. These containers are more memory efficient than using a HashMap to map Integers to Objects.

Below are the example code to create SparseArray:

SparseArray sparseArray = new SparseArray();
sparseArray.put(1, “Value1”);

SparseLongArray sparseLongArray = new SparseLongArray();
sparseLongArray.put(1, 1L);

SparseBooleanArray sparseBooleanArray = new SparseBooleanArray();
sparseBooleanArray.put(1, true);

SparseIntArray sparseIntArray = new SparseIntArray();
sparseIntArray.put(1, 2);

This way you make your code more optimized and memory efficient. To understand SparseArray and ArrayMap refer my detailed post.


How to trace memory issues?

Android Studio provides profiling tools to records and compute memory allocations of your app. Allocation Tracker are such a powerful tools which shows object allocation and their size. It is also used to track memory leaks.

Another good tool is Traceview, which is a graphical viewer for execution logs that you create by using the Debug class to log tracing information in your code


Conclusion

Now a day’s most of the applications are handling thousands of data, so any optimization you make could potentially improve the performance across our application. Small change of Autoboxing matters a lot for a mobile developer where you have very limited memory and resources.

To find more interesting topics on Software development follow me at:

Medium      Twitter     Google+

Comments

  1. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.

    Android Online Training

    ReplyDelete
  2. wow A Wonderful website I like this blog very much.This blog can help lot of user to update their knowledge.Thanks for sharing this kind of blog.Anybody want to learn
    http://www.traininginannanagar.in/android-training-in-chennai.html

    ReplyDelete
  3. wow A Wonderful website I like this blog very much.This blog can help lot of user to update their knowledge.Thanks for sharing this kind of blog.Anybody want to learn

    Android Training in Chennai

    ReplyDelete
  4. You have post an very useful blog about android. Its very interesting and useful to me and i have learn lots of new information from your blog share. keep update such kind of interesting stuff. thank you...
    Android Training in Chennai

    ReplyDelete
  5. Your blog have a very nice informative content on Android Online Training

    ReplyDelete
  6. The information related to the autoboxing is really informative... Wish to learn Android from the basics to the advanced level, enroll you in the Best Software Training Institute in Velachery to learn quickly...
    Android Training Institute in Velachery | Best Android Training Institute in Velachery

    ReplyDelete
  7. Nice to read this article... Thanks for sharing.......
    Android training

    ReplyDelete
  8. Nice information, check it once through Android Online Training for more info.

    ReplyDelete
  9. Thank you so much for sharing this great blog.Very inspiring and helpful too.Hope you continue to share more of your ideas.I will definitely love to read.
    Android Training in Chennai

    ReplyDelete
  10. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this. Android Training in Chennai

    ReplyDelete
  11. Thanks for above information, I like it. check it once Android Online Training

    ReplyDelete
  12. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    Android Training In Chennai

    ReplyDelete
  13. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    python training institute in marathahalli
    python training institute in btm
    Python training course in Chennai

    ReplyDelete
  14. Nice blog. Thanks for explaining the Android concept, Autoboxing in detail. Keep sharing the latest updates about Android.
    Android Application Development company in Coimbatore
    iOS Application Development Company in Coimbatore

    ReplyDelete
  15. Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.

    Amazon web services Online Training |Best Online AWS Certification Course
    AWS Training in Chennai | Advanced Amazon Web Services Training Institute in Chennai
    AWS Training in Bangalore |Best AWS Training in Bangalore

    ReplyDelete
  16. This pretty much applies to every job profile. Dissatisfaction , politics and people expecting you to know and do everything . I believe job positions that are extremely close to business side of things will be more rewarding . Decisions you take and mistakes you make must have the shortest path to revenue impacts , That is a place where you will be respected.
    Java training in Chennai | Java training institute in Chennai | Java course in Chennai

    ReplyDelete
  17. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me 
    Python Online certification training
    python Training institute in Chennai
    Python training institute in Bangalore

    ReplyDelete
  18. Wow...What an excellent informative blog, really helpful. Thank you so much for sharing such a wonderful article with us.keep updating..
    salesforce Training in Bangalore
    uipath Training in Bangalore
    blueprism Training in Bangalore

    ReplyDelete
  19. very interesting informative post.Thanks you so much for the post and the tips for users.I love the post a lot and intreseted to know more about it
    amazon webservices training institute in pune

    ReplyDelete
  20. The information provided is of great use as I got to learn new things. Keep Blogging.Best Android Training Institute


    ReplyDelete
  21. I think you did an awesome allahabad university BA 3rd year result job explaining it. Sure beats having to research it allahabad university bsc 1st year Result on my own. Thanks

    ReplyDelete
  22. Nice read, I just passed this onto a friend who was doing a little research on that. Jungle Cruise Full Movie 2021

    ReplyDelete
  23. Writing this type of article is one of the most important things you will ever learn. This is the type of articleBuy tinder accounts you will use to build your reputation as an author and also one that will help you get started in a career that is very profitable. Many people will ask me what I consider to be the most important part of this type of article. The answer is simple, the title. You need to create a quality title for your article before submitting it for publication.Buy snapchat account

    ReplyDelete
  24. Great Blog!
    I appreciate the depth of knowledge you bring to your writing. Thanks for sharing. If you want to hire dedicated Android app developers for the project. Join us!

    ReplyDelete
  25. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

Android O: Impact On Running Apps And Developer Viewpoint

Android Performance: Avoid using ENUM on Android

Local Broadcast, less overhead and secure in Android