Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB7
Expertise: Intermediate
Jul 6, 2002

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 values
Dim ba As New BitArray(1024)
' set the first element
ba(0) = True
' read it back
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 ba2
Francesco Balena
Comment and Contribute








