* WebAssembly: optimized SysOSAlloc to use memory area left at the end of the

page (64kb). This reduces memory use, when SysOSAlloc is called with sizes,
  smaller than 64kb.
This commit is contained in:
Nikolay Nikolov 2024-08-04 18:04:05 +03:00
parent a0c11becde
commit 6be3a42a2f

View File

@ -46,21 +46,29 @@ const
err = high(longword); err = high(longword);
var var
res: ptruint; res: ptruint;
avail: SizeUInt;
grow_pages: LongInt;
begin begin
{$ifdef FPC_WASM_THREADS} {$ifdef FPC_WASM_THREADS}
if InitialHeapCriticalSectionInitialized then if InitialHeapCriticalSectionInitialized then
EnterCriticalSection(InitialHeapCriticalSection); EnterCriticalSection(InitialHeapCriticalSection);
{$endif FPC_WASM_THREADS} {$endif FPC_WASM_THREADS}
if (PtrUInt(InitialHeapBlockEnd)-PtrUInt(InitialHeapBlockStart))>=size then avail:=PtrUInt(InitialHeapBlockEnd)-PtrUInt(InitialHeapBlockStart);
if avail>=size then
begin begin
SysOSAlloc:=InitialHeapBlockStart; SysOSAlloc:=InitialHeapBlockStart;
Inc(InitialHeapBlockStart,size); Inc(InitialHeapBlockStart,size);
end end
else else
begin begin
res:=fpc_wasm32_memory_grow((size + WasmMemoryPageSize - 1) div WasmMemoryPageSize); grow_pages:=(size-avail+WasmMemoryPageSize-1) div WasmMemoryPageSize;
res:=fpc_wasm32_memory_grow(grow_pages);
if res<>err then if res<>err then
SysOSAlloc:=pointer(res*WasmMemoryPageSize) begin
SysOSAlloc:=InitialHeapBlockStart;//pointer(res*WasmMemoryPageSize)
Inc(InitialHeapBlockStart,size);
Inc(InitialHeapBlockEnd,grow_pages*WasmMemoryPageSize);
end
else else
SysOSAlloc:=nil; SysOSAlloc:=nil;
end; end;