As far as I know, most "serious" VM implementations, such as CPython and the Oracle JVM, do not request new memory from the operating system ("malloc()") each time they create a new object.
As far as I understand it, these VMs usually request a large chunk of memory once, and then manage it internally for allocating objects as the program is running. (Pretty sure Oracle JVM requests all memory once at startup, and CPython requests blocks of memoriesmemory as it goes).
I'd like to understand - how is this approach better / more performant than simply requesting memory from the OS ("malloc()"?) each time the VM needs it?
As a more specific question - is code B more performant than code A? Why?
Code A:
Thing* allocate_thing(void) {
Thing* thing = malloc(sizeof(Thing));
thing_init(thing);
return thing;
}
Code B:
static uint8_t* memory_buffer = NULL;
static int bytes_offset = 0;
void init_memory_buffer(void) {
/* called once at beginning of program */
memory_buffer = malloc(1024 * 1024);
}
Thing* allocate_thing(void) {
Thing* thing = (Thing*) &memory_buffer[bytes_offset];
thing_init(thing);
bytes_offset += sizeof(Thing);
return thing;
}