C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Memory: The GC.GetTotalMemory method gathers the memory usage figures from the system before and after the allocation of the byte array.
GC.CollectThen: The byte array variable is assigned a reference to 3 million bytes in an array allocated on the managed heap.
Result: Allocating a 3 million element array of bytes causes 3 million bytes to be added to the memory usage of the program.
ValueTypeTip: Here we find that a byte array is a precise representation of bytes, not a higher-level construct.
C# program that allocates byte array
using System;
class Program
{
static void Main()
{
byte[] array1 = null;
//
// Allocate three million bytes and measure memory usage.
//
long bytes1 = GC.GetTotalMemory(false);
array1 = new byte[1000 * 1000 * 3];
array1[0] = 0;
long bytes2 = GC.GetTotalMemory(false);
Console.WriteLine(bytes2 - bytes1);
}
}
Output
3000032
C# program that uses File.ReadAllBytes
using System;
using System.IO;
class Program
{
static void Main()
{
byte[] array = File.ReadAllBytes("C:\\profiles\\file.bin");
Console.WriteLine(array[0]);
Console.WriteLine(array[1]);
Console.WriteLine(array[2]);
}
}
Output
56
66
80
Here: We load a JPG image on the disk into a byte array, and then encode it as a string. This can be put in CSS or HTML files directly.
ToBase64StringStringsC# program that uses ToBase64String
using System;
using System.IO;
class Program
{
static void Main()
{
byte[] data = File.ReadAllBytes(@"C:\Codex\i\2d-adventurers-map-background.jpg");
// Get base 64.
string result = Convert.ToBase64String(data);
// Write first 20 chars.
Console.WriteLine("BASE64: " + result.Substring(0, 20) + "...");
}
}
Output
BASE64: /9j/2wCEAAgGBgYGBggG...
Note: The first part of Main reads in a GZIP file, "2About.gz". The result value from IsGZipHeader on this file is true.
GZipTool: This class is a public static class, which means you can access it from other namespaces and files. It contains IsGZipHeader.
IsGZipHeader: This method returns true if the byte data passed to it contains the values 31 and 139 in its first two bytes.
C# program that tests gzip files
using System;
using System.IO;
class Program
{
static void Main()
{
byte[] gzip = File.ReadAllBytes("2About.gz");
Console.WriteLine(GZipTool.IsGZipHeader(gzip));
byte[] text = File.ReadAllBytes("Program.cs");
Console.WriteLine(GZipTool.IsGZipHeader(text));
}
}
/// <summary>
/// GZIP utility methods.
/// </summary>
public static class GZipTool
{
/// <summary>
/// Checks the first two bytes in a GZIP file, which must be 31 and 139.
/// </summary>
public static bool IsGZipHeader(byte[] arr)
{
return arr.Length >= 2 &&
arr[0] == 31 &&
arr[1] == 139;
}
}
Output
True
False
However: In some cases, this actually duplicates the Windows file system cache mechanism that is optimized for this exact purpose.
Note: Byte array caches on the file system can improve or degrade performance in various situations.