Byte arrays hold data in an efficient way. Any file can be read in, or downloaded, into a Byte array. Often this is much more efficient than other representations.
Data in a Byte array is sometimes harder to manipulate and read. Often strings or string
arrays are a better storage format.
We measure byte
array memory use. We allocate a Byte array. The reference to the Byte array requires 4 or 8 bytes on the stack.
byte
element requires exactly 1 byte
. But there are additional costs involved.Module Module1 Sub Main() 'Get memory. Dim value1 As Long = GC.GetTotalMemory(False) ' Create an array of 3 million bytes. ' ... We specify the last index to create an array. Dim bytes(1000 * 1000 * 3 - 1) As Byte bytes(0) = 0 ' Get memory and print the change. Dim value2 As Long = GC.GetTotalMemory(False) Console.WriteLine(value2 - value1) ' Ensure we have exactly 3 million bytes. Console.WriteLine(bytes.Length) End Sub End Module3000032 3000000
The BinaryReader
and BinaryWriter
types are often used with Byte arrays. It is possible to use a Byte array, wrapped in a MemoryStream
, with these types as a backing store.
File.ReadAllBytes
Function. Then we wrap the Byte array in a MemoryStream
.MemoryStream
to a BinaryReader
. We can use the Byte array, which stores a JPG image now, in the same way as a file.Imports System.IO Module Module1 Sub Main() ' Byte array stores a JPG. Dim array() As Byte = File.ReadAllBytes("C:\athlete.jpg") Using memory As MemoryStream = New MemoryStream(array) Using reader As BinaryReader = New BinaryReader(memory) ' Display values of first two bytes of JPG in memory. Console.WriteLine(reader.ReadByte()) Console.WriteLine(reader.ReadByte()) End Using End Using End Sub End Module255 216
To create an array of 3 million elements, we must specify the last required element index, which is 3 million minus one. This is a key difference between VB.NET and C#.
A Byte array is a versatile type. It stores a direct, accurate representation of binary data. This includes images (JPG, PNG) as well as many different file formats.