Review the Byte and SByte types. Measure the memory usage of Bytes and Byte arrays.
Byte. This is a fundamental unit of memory. It contains eight bits. Other types such as Integer are measured in terms of bytes. A byte is the smallest addressable unit. To change bits, bitwise operators must be used.
Example. Let's use the Byte type. Just like an Integer, the Byte can be declared and initialized in a Dim statement. Next we see that the Byte's minimum value is zero. The maximum value is 255.Integer
Note: If you try to assign a negative value to Byte, a compile-time error may occur.
And: If the compiler cannot detect the error on its own, runtime behavior may be unexpected.
Alias: This type is aliased to the System.Byte type. System.Byte is a composite name—it is easier to just specify Byte in your VB.NET program.
VB.NET program that uses Byte type
' Byte variable.
Dim value As Byte = 5
' Min and Max.
' Memory usage (allocate 1 million and 1 elements).
Dim a As Long = GC.GetTotalMemory(False)
Dim arr(1000 * 1000) As Byte
arr(0) = 1
Dim b As Long = GC.GetTotalMemory(False)
Console.WriteLine((b - a) / (1000 * 1000))
You can guess how many bytes are contained in each Byte element in an array. But for completeness I measured it. The program returns about 1 byte per Byte element. There is a little extra on the result.
Tip: The program allocates 1 million and 1 elements in the array—in VB.NET, we specify the last index, so we have an extra element.
Tip 2: When an array is allocated in a VB.NET program, it requires both memory for the array reference, and the array object data.
Storage locations. The reference is often stored on the evaluation stack in the virtual execution environment. But the array object data is always stored in a separate place—the managed heap.Array
Array. The Byte type is probably most useful when used as part of an array type. An array of bytes can store any complete file in memory. This can be useful for optimizations such as caches.Byte Array
Also: Byte can be beneficial for when file formats need to be read or parsed at the level of the binary. The BinaryReader type is helpful.
SByte. A Byte is unsigned—it has no sign bit. But SByte is a signed Byte—it has the same representation size but includes a sign bit. So it can store the values -128 (its MinValue) through 127 (its MaxValue).
VB.NET program that uses SByte
' Display minimum and maximum values for SByte.
Dim value As SByte = SByte.MinValue
value = SByte.MaxValue
Summary. A Byte requires one byte of memory. It can store values between, and including, zero and 255. It has no sign bit so cannot store a negative value. Byte arrays represent binary data files in memory.