DEV Community

loading...

Discussion on: How Does Svelte Actually Work? part 1

Collapse
glebec profile image
Gabriel Lebec

Oh man, Svelte uses bitmasks? That is the first time I have seen someone use them in prod. A bitmask is a compact way to store N boolean flags in a single N-bit integer. JS numbers are IEEE 754 64-bit floats, but when you do certain ops they are shortened to 32 bits, so you can safely store 32 bools in a single JS number. When you & x, you check if the digit in place 2x-1 is a 1 or a 0. Suppose dirty = 13; then in binary, dirty is 1101. If you do dirty & 1 you get 1 (the lowest bit). If you do dirty & 2 you get 0 (the second lowest bit). So if you use the lowest bit to store whether name is dirty, and the second lowest bit to store whether number is dirty, then in the case of dirty = 13, they are dirty and not dirty respectively!

This also means that if you need to store more than 32 prop dirty states, Svelte will need more numbers to cram the states in as bits. But if this is per-component, I doubt many people exceed 32 props in a component. Neat!

Collapse
zev profile image
Zev Averbach Author

Thanks Gabriel! Mystery solved, once I wrap my head around this.

Collapse
glebec profile image
Gabriel Lebec

Two good resources for understanding bitmasks in this context: