IntSet Development
Abstract
On 2023-11-21, I developed a set container for JavaScriptbigints. This allows for unions, intersections, and other set operations, but in a relatively fast manner. This blog post describes my development methodology, the issues I faced, and how I overcame them. Table of Contents
tl;dr, Don’t use more than 16k values, and don’t have a variance greater than 65k between the minimum and maximum values.
Preamble
The purpose of IntSet is to act as a container for bigints by utilizing bit masks and bitwise operators. This would improve the runtime performance and reduce memory use compared to traditional methods, assuming the contents of the sets are “relatively close” to one another.
“Relatively close”, meaning the spread of integers within the set, or the range of values (the difference between the minimum value and maximum value) is lower than 65k. The reason why is discussed in the benchmarks.
Traditionally, if you have a group of values you need to retain, the everyday programmer would choose something simple like an array and manually check for uniqueness, while others would look to a tree-like structure like a binary tree, or better, a red-black tree, to contain the data. These are easy solutions, and doesn’t require much thought, but the performance of these structures matters when dealing with high throughput (either data or operations). Arrays grant insertion, but harbor for search and deletion. A red-black tree will grant for all three operations in the worst case, but we can do better.
This blog post is an account of my development experience for this library, and a slight technical interlude on how it works. The audiance reading this should be familiar with basic set theory, JavaScript, and bits.
Before I go any further into the implementation, I’d like to describe the bit masking and how it works.
Bit Masking
Assume you have some non-negative real integer (natural number) . Also, assume you have a bit space (where you can freely write and read bits at certain indicies), represented as array of bits with length . For instance, a 32-bit integer consumes 32 bits of space, and in that circumstance, .
If , then can be represented as a single bit flipped in the space provided by ; is the first bit, is the second bit, is the third bit, and so on. If you were to turn the bit space into a (little-endian / right-to-left) integer , and if ’s bit were the only bit flipped in the bit space, then .
As an example, let’s say , and . In this case, the value of the first bit is , and the value of the of the rest of the bits would be . If we turn this bit space into a integer , it would equal – in other words, . You can try this in JavaScript – the bit space would be written (using binary notation) as 0b00000001, and JavaScript will tell us this value is actually just 1 (our ).
const m = 0b00000001;
console.log(m);
// → 1Or, let’s say that , and again. In that instance, ’s 8th bit is , and the rest are ’s - it would look like 0b10000000 in JavaScript. Again, if we were to evaluate this, it would return 128, which is the same as .
const m = 0b10000000;
console.log(m);
// → 128Bitwise Or and Union
Now lets imagine the union of these two examples – we’ll “zip” the bit spaces together, and if either of each compared bit has a value of , we’ll retain it. Doing this with our previous examples of 0b00000001 and 0b10000000 would return 0b10000001, which when evaluated in JavaScript would reveal 129:
const m = 0b10000001;
console.log(m);
// → 129What we mean by this bit space is “both the values of and are present in the bitspace ”.
Fortunately, JavaScript (and in fact, most CPU architectures) implement this bitwise union through the bitwise “OR” operator |. We can try running 128 | 1 and 0b10000000 | 0b00000001 in JavaScript, and we’ll receive the result 129:
console.log(128 | 1);
// → 129
console.log(0b10000000 | 0b00000001);
// → 129What does this imply?
Given a contiguous bitspace with a size , all natural numbers less than the bitspace size ( such that ) can be represented in the bitspace via the presence of its th bit.
Furthermore, given a set of natural numbers less than the bitspace size (), where each member of the set is referred to as (i.e., there are elements in ), the bitspace can be represented as:
Where is the whole integer that represents the set , and is the bitwise or operator |. These implications are expanded on the other operators as well:
| Bitwise Operator | Set Operator |
|---|---|
| / OR | / Union |
& / AND | / Intersection |
^ / XOR | / Symmetric Difference |
With these primitive operations, the difference operation can be defined as follows:
Unbounded Data
Now that we have a mechanism to create sets of natural numbers up to size , we need one that could be (mostly) unbounded.
A first stab – Arrays
Initially, I imagined am array of ’s to be the most intuitive solution – the bit space representation of a set of any value is an array of length elements, each of which holds an , with bit size of . The value of an th bit in a th bitspace is calculated as follows:
Note, is the ceiling operation.
Where is the (zero-based) index in the array that contains .
Implementations of setwise union, intersection, and the like would be performed through zip-with – where in the case of union and symmetric difference, the elements not present in the other are simply retained as-is – the resulting array between sets with arrays and would be the maximum of and .
Issues with Arrays
The critical issue with this solution is the case where the set only holds large values. In that circumstance, there will be wasted -valued elements denoting orders of magnitude, up until the relevant value – essentially, this makes the size of the set linear with respect to the maximum value of regardless of the count of elements contained within the set, and likewise the setwise uperations would be .
This is unacceptable, and a better solution exists.
A better stab – Maps
Rather than store empty values, we can sparsely store values if they are greater than 0 by utilizing the built-in Map object in ECMAScript 6 – Now, we can store the values with the index as its key:
This causes for a great deal of efficiency where values are relatively near to each other. Particularly, if the average difference between values are below , then they’ll (likely) be stored in the same value, regardless of how large the values are.
Implementation
The code lives in my personal GitHub, and can be inspected very easily - it’s only a few hundred lines.
I tried to be thorough with the tests and benchmarks, however the latter are a bit difficult to parse, but they did help me choose a good default value. I am confident with the default settings of IntSet, but if you’d like to customize , it can be supplied as an argument to new IntSet(n).
Tests
The tests are built using property-based testing techniques, namely via a fuzz tester library for JavaScript called fast-check. The following invariants are tested:
| Name | Expression |
|---|---|
| Existence | |
| Non-Existence | |
| Union Commutativivty | |
| Union Identity | |
| Union Associativity | |
| Intersection Commutativivty | |
| Intersection Absorption | |
| Intersection Associativity | |
| Symmetric Difference Commutativivty | |
| Symmetric Difference Identity | |
| Symmetric Difference Absorption | |
| Symmetric Difference Associativity | |
| Difference Identity | |
| Difference Absorption | |
| Difference / Union Intersection Equivalence | |
| Difference / Union Symmetric Difference Equivalence |
I’ve deemed this to be a pretty thorough test suite. If you feel like more properties should be represented in the test suite, please feel free to file a bug report.
Note: in the above contexts is defined as the set of all
IntSets.The empty set is defined as
Such that
Benchmarks
The benchmark suite is, in my opinion, sub-standard. I originally built it to try and find a good default value for ; my assumption was that would be a good value, but I wanted to verify.
I have two forms of benchmarking suites - the first uses Benchmark.js to find a “fastest” version of the union function, and the second takes a heap snapshot of the union function of the same two sets, and also measures the approximate total amount of data stored in that resulting set. The data being generated are two sets, each of which are filled with random bigints, with maximum value of , and implementations of varying between . The following figures show the results:
Interpretations
A few observations can be made by these figures. First, let’s start with Operations Per Second:
- Sets maximize speed for random numbers generated up to when .
- Sets maximize speed for random numbers generated up to when .
- Before the speed is maximized, the approach to obtaining higher speed at a particular max random value comes at a curve.
- The entire space past for maximum size is pretty flat - no drastic speed increases.
Secondly, Heap Used:
- The dominating factor is the maximum value of the generated numbers, not .
- ’s increase does have a minor factor past , especially in the extreme cases of .
Lastly, Total Size:
- Total size appears to gain exponential growth past , and can be directly observed with an increase in .
Unfortunately, the last figure doesn’t give us a great deal of insight to the (potential) total amount of memory used, but rather a philosophical perspective, which is why I included the “Heap Used” figure as well.
Given that concern, I’ve opted to reduce the chart’s ranges a bit for these next figures - will not exceed , and the max number generated will not exceed .
Further Interpretations
From the latter two figures, a reasonable conclusion can be observed – space consumed by sets are relatively constant up until the maximum number generated becomes greater than . This, however, may be indirectly related to the fact that there are only numbers in each set; smaller generated values would likely exhaust the sample space.
Additionally, although the assumed spatial consumtion of the sets (last figure) is assumed to increase as increases, we can see that for cases where the maximum generated number is greater than , the heap is actually larger for smaller values of . I assume this to be due to the operational overhead, i.e. callbacks and the like, because of the need to “mesh” more values together.
Conclusion
There are a few key points to receive from this investigation:
- Potential gains from this library are drastically diminished when the set contents can be larger than , both in terms of speed and space.
- For values generated up to , I recommend a default value of , due to the clef in the Reduced Operations Per Second at .
- For values generated up to , I recommend an value of .
- For larger values, maybe consider a different library.
Considerations
A few potential deficiencies should also be identified:
- I only benchmarked
union, not the other set-wise operations. - I only benchmarked sets that have elements, not fewer ones.
- I used
Math.random()to generate the random numbers – there may be a lack of uniformity in the random numbers being generated.
However, I don’t want to address those at this time. I hope you enjoyed this exploration! It was very insightful for me.