Home > Software design >  How do I know what is the size limit for constructing a Set in JavaScript?
How do I know what is the size limit for constructing a Set in JavaScript?

Time:06-30

I am making a tool for deleting geometry from a model in browser.

At some step of the deletion process, I take an array full of indexes and create a Set from it to get the array of unrepeated indexes.

function GetSetFromArray(array){
    return new Set(array);
}

This function has worked good for many models at the beginning. Since I want to process the deletion as fast as possible, I wanted to avoid using solutions that require .indexOf.

But when I try to delete from a big model, for example, an array with a length of roughly 15,000,000. I get the following error on the browser's console:

Uncaught (in promise) RangeError: Set maximum size exceeded

console error screenshot

I want to know, what is the maximum size for creating a Set? Is it something that depends on the Browser? Or on the PC running the Browser? Is there a way to get that number? I think that maybe if I could get the size limit of the Set, I could then split the array to make a series of Sets and then use that?

CodePudding user response:

The collection containing the items in a Set is called a "List" in the specification, and a limit on the size of a List is not specified.

These sequences may be of any length

Nor is the size of Set lists in particular specified. (1, 2)

  1. Set set.[[SetData]] to a new empty List.

So, it must be implementation-defined.

Is it something that depends on the Browser? Or on the PC running the Browser?

It will depend on the JavaScript engine the browser uses (for example, V8, or SpiderMonkey, or JavaScriptCore, among others).

Is there a way to get that number?

Just .add items to a Set until it throws.

const getSetSizeLimit = () => {
  let i = 0;
  const set = new Set();
  while (true) {
    try {
      set.add(i);
    } catch(e) {
      return i;
    }
    i  ;
  }
  return i;
};
console.log(getSetSizeLimit());

On my Windows-Chrome, the limit looks to be 16777216, which is 2 ** 24.

  • Related