TheAlgorithms / C-Sharp

All algorithms implemented in C#.
GNU General Public License v3.0
6.91k stars 1.48k forks source link

BitArray could be using way less memory #397

Closed Bamboy closed 11 months ago

Bamboy commented 1 year ago

I was very surprised to see that BitArray uses bool[] as an underlying type. If you didn't know, the bool type in C# actually allocates an entire byte of memory because that is the minimum addressable size used by the CLR. You waste 7 bits for every bool. See https://stackoverflow.com/questions/2308034/primitive-boolean-size-in-c-sharp/2308052

I see @LorenzoLotti was the original contributor so I'm tagging them.

A maximum performance gain would be to use byte[], int[], or long[] as the underlying data type and then use bitwise operations to get the bit value you actually want.

This improvement seems minor compared to the effort to implement, but could maximize memory usage for very large data sets.

siriak commented 1 year ago

Thanks for reporting this. There are some things that are worth replacing in the current implementation like using strings in & and | operators, but I think having a bool as the underlying type is not a problem in educational sense. Yet, we can have 2 implementations BitArraySimple (current) and BitArrayOptimized (using byte and using storage efficiently)

Bamboy commented 1 year ago

A bit of a selfish note about why I mentioned this issue: I have been making Asteroidians, a worms type game with 2D per-pixel destructible terrain and I store collision data as bool[,]. This works fine as is, but does introduce some bottlenecks which could be alleviated by switching to a single dimensional array of byte[]. Unfortunately I am complete ass at the implementation of math stuff in general.

This would not solve all of my performance issues as many of my implementations of algorithms (such as Bresenham's Line Algorithm) are still iterating on a bool by bool basis. Especially the circle drawing algorithm I use (I forget which) would be way faster if it operated on a byte level.

Not looking for free handouts - just sharing my use case :)

github-actions[bot] commented 11 months ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.

github-actions[bot] commented 11 months ago

This issue was closed because it has been stalled for 7 days with no activity.