Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Android allocate more memory than needed when loading images

Folks, I don't think that this is a duplicate and is NOT one of those how do I avoid OOMs questions. This is a genuine quest for knowledge so hold off on those down votes please...

Imagine I have a JPEG of 500x500 pixels. I load it as ARGB_8888 which is as "bad as it gets".

I would expect Android to allocate 500x500x4 bytes = a little under 1MB however, look at a heap dump and you will see that Android allocates significantly more, often factors of 5-10 times greater.

You frequently see questions on here about OOMS where the stack trace shows a heap request of say 15MB and it is Always much larger than is required simply to hold the bytes of the image. The OP usually catches some downvotes then is bombarded with stock answers and comments about using less memory (thanks Romain!) and in scaling. I think there is more than meets the eye here.

Anybody know why this is?

If there is no apparent answer, I will put together an SSCCE if it helps.

PS. I assume that JPEG vs PNG etc is irrelevant since we're talking about the memory usage of the backing bitmap which is simply x times y times BPP - or am I being slow?

like image 646
Simon Avatar asked Nov 10 '12 15:11

Simon


1 Answers

It used to be quite a common trick with memory management to grab a pool or block of memory which is parceled out into smaller requests. When I worked with embedded systems it was a common practice to maintain pools of memory of different sizes, and we just allocated a block larger than the amount requested from a pool . It is a convenient way of preventing too much memory fragmentation. Maybe this is happening here.

like image 102
vogomatix Avatar answered Oct 26 '22 23:10

vogomatix