2

I am getting an OutOfMemoryError when I try to create a String larger than 4MB using StringBuilder.append().

As far as I know, StringBuilder doesn't have any limitations regarding size and so doesn't String.

So I searched for "how to increase Android heap size" and as far as I could conclude from this answer and this answer, Gingerbread is the only version in which you have no way of dealing with the heap size, since for earlier versions you use the VMRuntime class and for newer versions android:largeHeap="true" on the Manifest.

Is that assumption correct? What do you do when you're in between VMRuntime and android:largeHeap="true"?

I used Runtime.getRuntime().totalMemory()/1048576 - Runtime.getRuntime().maxMemory()/1048576 to get "5.00 MB allocated of 42.00 MB available" on the device I'm using for tests (Android 2.3.6).

Community
  • 1
  • 1
Nick Fanelli
  • 265
  • 1
  • 6
  • 19
  • I'd call this an X Y Problem: You shouldn't be looking for a way to increase the memory. You should be looking for a way to fix that you're building 4MB Strings in memory. – zapl Nov 07 '14 at 13:51
  • @zapl Sometimes when dealing with legacy systems you have no choice. – Michael Dec 30 '14 at 04:42

1 Answers1

2

Is that assumption correct?

I cannot say whether VMRuntime ever worked. android:largeHeap is definitely something for API Level 11+.

What do you do when you're in between VMRuntime and android:largeHeap="true"?

Find a more memory-efficient way of building your 4MB String, such as by providing a large capacity to your StringBuilder constructor.

Or, find a way to implement whatever it is that you are doing without creating a contiguous 4MB String.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Interesting, @CommonsWare Mark! So you don't get to play with the heap when you're in Gingerbread, but it does grow in certain scenarios. I used `StringBuilder`'s `ensureCapacity(8388608)` to ensure it would allocate 8MB to it. And sure enough, I got a "_dalvikvm-heap | Grow heap (frag case) to 33.268MB for 8388624-byte allocation_" message ... and the error is gone. A contiguous large random `char` `String` is being used so less write operations are needed to create a file with maximum file size. Do you suggest any other wiser approaches? – Nick Fanelli Nov 07 '14 at 15:07
  • @NickFanelli: " A contiguous large random char String is being used so less write operations are needed to create a file with maximum file size" -- in particular, because Dalvik does not have a compacting garbage collector, you are not fragmenting your heap quite so much. "Do you suggest any other wiser approaches?" -- other than avoiding the really big `String` in the first place (somehow), no.. – CommonsWare Nov 07 '14 at 17:41