C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
And: The 3 million elements, bytes, of the array require a bit less than 3 megabytes of memory.
Important: In an array, each byte element requires exactly 1 byte. But there are additional costs involved.
Program: This example uses a Byte array but not in a useful way. Byte arrays are useful as storage regions for images or binary data.
VB.NET program that creates Byte array
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 Module
Output
3000032
3000000
Info: This is an efficient approach to reading bytes, as it does not access the hard disk more than once.
BinaryReaderHere: We use the File.ReadAllBytes Function. Then we wrap the Byte array in a MemoryStream.
And: We pass that MemoryStream to a BinaryReader. We can use the Byte array, which stores a JPG image now, in the same way as a file.
FileVB.NET program that uses Byte array
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 Module
Output
255
216
Note: Thanks to David Deley for pointing out an error in a previous version of the byte array program.