Skip to content

numbers.js cache excessive memory usage #139

@David-Parker

Description

@David-Parker

The uint16 cache from numbers.js currently consumes roughly 10Mb, which is too excessive for our application.

We could disable the precache generation, but I think the implementation could be improved.

Currently the cache is an object that maps indexes from 0 to 65535 to 65536 individual Uint8Array objects (using Buffer.allocUnsafe). Each one of these Uint8Array objects is consuming 72 bytes on Chrome (when it's supposed to be representing 2 bytes of unsigned integer data, but each Uint8Array object has quite a bit of overhead).

Another potential issue is we are forcing Big Endian encoding by serializing the bytes manually:

  buffer.writeUInt8(i >> 8, 0)
  buffer.writeUInt8(i & 0x00FF, 0 + 1)

Instead of creating this map of individual arrays, could the same cache be achieved using a single UInt16Array?

I.e.:

const max = 65536
const cache = new Uint16Array(max)

for (let i = 0; i < max; i++) {
  cache[i] = i;
}

With this implementation, the entire cache only consumes roughly 131Kb a significant decrease from 10Mb.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions