From 66a9d1ae4ff130e2d00d1f46d3b82b6cf3386e5a Mon Sep 17 00:00:00 2001 From: Brian Popow Date: Mon, 16 Aug 2021 18:39:28 +0200 Subject: [PATCH] Use ReadOnlySpan instead of stackalloc --- .../Formats/Jpeg/JpegEncoderCore.cs | 22 +++++++++++-------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs b/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs index ad05b298be..71f9827e27 100644 --- a/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs +++ b/src/ImageSharp/Formats/Jpeg/JpegEncoderCore.cs @@ -265,7 +265,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg private void WriteDefineHuffmanTables(int componentCount) { // Table identifiers. - Span headers = stackalloc byte[] + ReadOnlySpan headers = new byte[] { 0x00, 0x10, @@ -568,15 +568,17 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// The component Id's. private void WriteStartOfFrame(int width, int height, int componentCount, ReadOnlySpan componentIds) { + // This uses a C#'s compiler optimization that refers to the static data segment of the assembly, + // and doesn't incur any allocation at all. // "default" to 4:2:0 - Span subsamples = stackalloc byte[] + ReadOnlySpan subsamples = new byte[] { 0x22, 0x11, 0x11 }; - Span chroma = stackalloc byte[] + ReadOnlySpan chroma = new byte[] { 0x00, 0x01, @@ -585,7 +587,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg if (this.colorType == JpegColorType.Luminance) { - subsamples = stackalloc byte[] + subsamples = new byte[] { 0x11, 0x00, @@ -598,7 +600,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg { case JpegColorType.YCbCrRatio444: case JpegColorType.Rgb: - subsamples = stackalloc byte[] + subsamples = new byte[] { 0x11, 0x11, @@ -607,7 +609,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg if (this.colorType == JpegColorType.Rgb) { - chroma = stackalloc byte[] + chroma = new byte[] { 0x00, 0x00, @@ -617,7 +619,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg break; case JpegColorType.YCbCrRatio420: - subsamples = stackalloc byte[] + subsamples = new byte[] { 0x22, 0x11, @@ -658,7 +660,9 @@ namespace SixLabors.ImageSharp.Formats.Jpeg /// The componentId's. private void WriteStartOfScan(int componentCount, ReadOnlySpan componentIds) { - Span huffmanId = stackalloc byte[] + // This uses a C#'s compiler optimization that refers to the static data segment of the assembly, + // and doesn't incur any allocation at all. + ReadOnlySpan huffmanId = new byte[] { 0x00, 0x11, @@ -668,7 +672,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg // Use the same DC/AC tables for all channels for RGB. if (this.colorType == JpegColorType.Rgb) { - huffmanId = stackalloc byte[] + huffmanId = new byte[] { 0x00, 0x00,