Store large Boolean arrays in a BitArray object

Store large Boolean arrays in a BitArray object

.NET Boolean values require 4 bytes each, as opposed to the 2 byte taken under previous VB versions. When creating very large Boolean arrays this extra memory impacts negatively on the application’s performance. The .NET Framework offers a specialized class, the System.Collection.BitArray class, which lets you store a number of boolean values as if it were a regular array, yet it takes only 1 bit for each element.

You pass the capacity of the array – that is, the number of Boolean values you want to store – to the BitArray’s constructor, and then you write and read its elements as if it were a regular array:

' This code assumes that you have the following Imports'    Imports System.Collections' an array of 1024 boolean valuesDim ba As New BitArray(1024)' set the first elementba(0) = True' read it backConsole.WriteLine(ba(0))

All the elements in a freshly created BitArray are initialized to False, but you can set them to True by using the following constructor

Dim ba As New BitArray(1024, True)

or with the SetAll method

ba.SetAll(True)     ' or False

You can also pass a true Boolean array to the BitArray constructor, so that each element in the BitArray is initialized with the corresponding element in the original Boolean array.

Finally, you can perform bitwise operations on all the members of a BitArray by means of Not, And, Or, and Xor methods. All these methods (except Not) take another BitArray as an argument, so that all the elements of the current BitArray are combined with the corresponding element of the other BitArray according to the specified operation:

Dim ba1 As New BitArray(1024)Dim ba2 As New BitArray(1024)' initialize both BitArrays' ...' AND all the elements in ba1 with the elements in ba2ba1.And(ba2)

See also  5 Tips to Manage a Remote Workforce

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist