D
D
Dmitry Belyaev2016-08-04 22:39:57
JavaScript
Dmitry Belyaev, 2016-08-04 22:39:57

Is it possible for an asm.js module to replace heap-buffer without restarting the module?

The essence of the problem is that it is necessary to organize dynamically allocated memory for the asm.js module . As you know, as a virtual heap, it accepts an
ArrayBuffer whose dimensions cannot be dynamically changed . , copy the heap to a buffer of the right size and run the module with the new heap Maybe there are better ways?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-08-05
@bingo347

I figured it out myself (well, the comments from napa3um helped), I’ll post it here, maybe it’s useful to someone
. ArrayBuffer itself doesn’t eat anything memory yet
But if you create a typed array based on it in ordinary js, then the memory is eaten up by the size of the buffer
Example:

const heap = new ArrayBuffer(1 << 30); //создали буфер 1gb но память он пока не занимает
const heapUI16 = new Uint16Array(heap); // создали типизированный массив связанный с буфером
 // здесь будет сожрана память на весь буфер (1gb + доп данные от v8)
 // + будет большой такой лок процесса пока буфер забьется нулями, что плохо

Inside asm.js, typed arrays behave quite differently, they simply bind to the buffer, but do not fill it with anything and, accordingly, the memory is not consumed until we write something somewhere.
The actual solution:
Use in a regular js DataView to manipulate the heap from the outside, it also doesn’t fill the buffer with anything and doesn’t eat memory.
Example:
const heap = new ArrayBuffer(1 << 30); //создали буфер 1gb
const heapView = new DataView(heap); //интерфейс для управления heap снаружи

//asm.js модуль
const asmModule = (function(std, env, heap) { 'use asm';
var HUI8 = new std.Uint8Array(heap); //это памяти пока не съест

//...
}({Uint8Array}, null, heap));

//функция для помещения строки на heap
function alocateString(pointer, str) {
  heapView.setUint32(pointer, str.length);
  for(let i = 0, p = pointer + 4; i < str.length; i++, (p += 2)) {
    heapView.setUint16(p, str.charCodeAt(i));
  }
}

//поместим не в начало буфера, а куда нить на позицию в 1мб длинную строку, 8кб:
alocateString(1024*1024, 'test'.repeat(1024));
Voila, after adding 8kb to the buffer, the memory consumed by the process also grew by 8kb (well, with a penny)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question