Heap pre-allocation test to boost startup

In my current project, I seem to be able to stabilize the allocation speed by pre-allocating more than enough mem at start up.

Without pre-allocating my framerate stabilizes to 60 fps at around 15 seconds. When I pre-allocate I get steady 60 fps within 3 seconds of starting up.

If any of you guys have some spear time, try testing this out with your project an see if it actually does anything useful or its just me getting tired.

using UnityEngine;
using System.Collections;

public class Game : MonoBehaviour {
	
	class HeapBlock : System.IDisposable {
		public byte[] bytes = new byte[500000];
        public void Dispose() {}
	}
	
	Game () {
		if (!Application.isEditor) {
			using (HeapBlock block = new HeapBlock()) {
				for (int i=0; i<block.bytes.Length; ++i) {
					block.bytes[i] = 255;
				}
			}
		}
	}
	
	void Start () {
	}
}

I’m preallocating 500K, make sure you preallocate closer to your app needs. Check your profiler.

Makes sense that it helps actually. Reason is that memory allocation on the iphone is one of the most costly operations so if you allocate massive blocks and dispose them again, the GC actually does not “minimal allocate” memory but has a massive pool at hand right after this thingy is disposed.

Never thought of force allocating it though, so I would like to thank you for posting your experiment experience with it :slight_smile:

PS: You can do the same with textures, that should further help on stabilizing the fluedity. Just render a guitexture in front of everything and ensure that all textures used otherwise (if < 22mb VRAM together) are rendered behind it. That will upload all to the VRAM and thus prevent the micro stutter that otherwise can happen with large texture uploads

Actually, recent iPhone Unity docs do give that trick too in Optimizations chapter, but in a different way. I don’t recall it at the moment, but it’s not using the Heapblock class, only a Object builtin array and a byte().

Works perfectly for me, but I will try your method, thank you for that :wink:

In this case I wanted to force the pre-allocation before any call to Awake and Start.

Just wanted to see if I could strike ahead. I guess there is still a lot going on before a component gets constructed, and I’ll see if I can find how to get there before most allocations.

The only way to get further out is directly do it from the XCode project and access the mono there already to generate memory on the mono level itself instead of waiting till unity is initialized at all

right on !!!

I’ll be checking it out, and reporting my findings.

Great stuff :smile:

following dreamora’s advice…

this actually makes the profiler report the pre-allocation and avoids startup allocations :slight_smile:

look for the following code (in AppController.mm) and add the 2 lines

// --- Mono ---------------------------------------------------------------------
//
extern "C" {
	
        // add this line
	void *mono_gc_alloc_fixed      (size_t size, void *descr);
	

	long mono_gc_get_used_size();
	long mono_gc_get_heap_size();

then add this other line:

- (void) startUnity:(UIApplication*)application
{	
	[application setStatusBarHidden:TRUE];
	
        // add this other line
	mono_gc_alloc_fixed(1000000,NULL);
	
#if ENABLE_INTERNAL_PROFILER
	GC_notify_event = (void*)gccallback;
#endif

this is purely speculative, I’ll test this out more and see if its for real

these mono functions are not documented very well, I’ll download the mono source to take a real look into it

ensure to download mono 1.2.5, as unity is not using 2.x (although the AOT compilation for the iphone indicates some crossover thingy)

ok, found the other missing part here:

http://anonsvn.mono-project.com/viewvc/trunk/mono/mono/metadata/gc-internal.h?view=markup

managed to get a fixed heap pre-allocated :slight_smile:

now Unity allocates everything quickly at startup

change the following in AppController.mm:

// --- Mono ---------------------------------------------------------------------
//
extern "C" {
	
        // add these two lines
	void *mono_gc_alloc_fixed      (size_t size, void *descr);
	void mono_gc_free_fixed		   (void* addr);
	
	long mono_gc_get_used_size();
	long mono_gc_get_heap_size();
- (void) startUnity:(UIApplication*)application
{	
	[application setStatusBarHidden:TRUE];

	// add this line
mono_gc_free_fixed(mono_gc_alloc_fixed(1000000,NULL));
	
#if ENABLE_INTERNAL_PROFILER
	GC_notify_event = (void*)gccallback;
#endif

i would still recommend not using this unless you know how to debug it

How did the old logic go like? Ah yeah, “Force is not a solution but a good start”
I love bruteforce solution approaches :wink:

Will check that out on my prototype somewhen, sounds definitely promissing.
Perhaps 1.5.1 / 1.6 will offer a player setting or even better estimate a usefull value right from build and the scenes.

The combination of this + the heap allocation before level switches where needed (especially main menu to first real level) should help to reduce the time to “stabilize to normal” seriously :slight_smile:

Potentially this force approach could be used to check if the device offers enough memory for the game at all if you know that you have a memory peak at point X that requires at least XY bytes you could try to force allocate a fair amount of that there and if it fails you at least startup up time for the user and can inform him through a UIKit error message.

Didn’t have the time to test it yet, but how would this be bugged ?

Did you have the opportunity to check its efficiency ?

when launching from xcode i don’t see much improvement, but when launching directly on the device, the improvement is apparent, the fps stabilizes to 60fps in less than 3 seconds. Without it, usually takes more than 15 seconds.

The internal profiler provided by unity, shows that the big chunk of heap was allocated and is available (hopefully not fragmented).

I’m allocating 500K at start now, and its even faster than allocating 1M. My app uses up to 250K and peaks at around 400K. Seems like collecting 40K-80K of garbage takes around 3 milliseconds; not so bad if you’re above 50fps at the time of collection. There might be a magic number of when the collector kicks in proportionally to the amount of heap used before. A bigger pre-allocation causes the GC to collect later, causing a 6-9 millisecond spike. In any case, it should be trial an error, if it works at all.

I don’t recommend doing this, because I don’t know the internals of the functions I’m calling and this process might not be supported by mono nor unity. It’s not stopping me though, it should not stop you either :wink:

Great and precise feedback, thank you :wink:

Just checking if I get this right:
the first version of this approach would cause ONE garbage collection right away, right? I mean you allocate and release 500k so I expect that memory to be collected right after.
If that’s the case, does the second version (done in Application.mm) cause a collection too?

hi! sorry to bump this thread but I can’t find the code in appcontroller that I’m supposed to modify