0

Okay, so I have an app that works with several large data structures; for performance, these will over-allocate array sizes, and hold onto cleared spaces, in order to ensure it can expand quickly when new items are added, i.e - it avoids having to create new arrays as much as possible.

However, this can be a bit wasteful if a device is low on memory. To account for this I currently have some sanity checks that will shrink the arrays if the amount of unused spaces exceeds a certain amount within a certain amount of time since the last time the array size was changed, but this seems a bit of a clunky thing to do, as I don't know if the space actually needs to be freed up.

What I'm wondering is, if I have a method that tells my object to reclaim space, is there a way that I can detect when my app should release some memory (e.g - memory is low and/or garbage collection is about to become more aggressive), so that I can shrink my data structures? I ask because obviously some devices aren't very memory constrained at all, so it likely won't matter much if my app is a bit wasteful for the sake of speed on those, meanwhile others benefit from having as much free space as possible, but my current method treats both cases in exactly the same way.

Haravikk
  • 3,109
  • 1
  • 33
  • 46
  • What data structures, and what does your app do? – Anubian Noob Jun 06 '14 at 15:23
  • Have you looked into soft/weak references: http://stackoverflow.com/questions/299659/what-is-the-difference-between-a-soft-reference-and-a-weak-reference-in-java – Morrison Chang Jun 06 '14 at 15:33
  • Unfortunately weak references won't really help, as the excess memory I'm looking to prune is actually empty (`null` references) within arrays. I just need to know when to shrink them. – Haravikk Jun 07 '14 at 11:26

1 Answers1

1

is there a way that I can detect when my app should release some memory (e.g - memory is low and/or garbage collection is about to become more aggressive), so that I can shrink my data structures?

Override onTrimMemory() in relevant classes implementing ComponentCallbacks2 (e.g., your activities). In particular, states like TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_MODERATE, and TRIM_MEMORY_COMPLETE are likely candidate times to "tighten your belt" from a memory consumption standpoint.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I'm not sure why this was put on hold though, I thought the description was clear enough (I have big arrays and need to know when I should shrink them), but it looks like `onTrimMemory` is exactly what I'm looking for, thanks! – Haravikk Jun 07 '14 at 11:28