Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add string optimizations #521

Merged
merged 10 commits into from
May 13, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Utilize suggestions
  • Loading branch information
Shane32 committed May 11, 2024
commit 5037a5a3b0cd0ffe3482b80b12160feaadcd8d29
25 changes: 20 additions & 5 deletions QRCoder/QRCodeGenerator.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1
using System.Buffers;
#endif
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
Expand Down Expand Up @@ -937,29 +940,41 @@ private static BitArray PlainTextToBinaryByte(string plainText, EciMode eciMode,

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1
// We can use stackalloc for small arrays to prevent heap allocations
// Note that all QR codes should fit within 3000 bytes, so this code should never trigger a heap allocation unless an exception will be thrown anyway.
const int MAX_STACK_SIZE_IN_BYTES = 512;

int count = targetEncoding.GetByteCount(plainText);
Span<byte> codeBytes = count < 3000 ? stackalloc byte[count] : new byte[count];
byte[] bufferFromPool = null;
Span<byte> codeBytes = (count <= MAX_STACK_SIZE_IN_BYTES)
? (stackalloc byte[MAX_STACK_SIZE_IN_BYTES])
: (bufferFromPool = ArrayPool<byte>.Shared.Rent(count));
codeBytes = codeBytes.Slice(0, count);
targetEncoding.GetBytes(plainText, codeBytes);
#else
byte[] codeBytes = targetEncoding.GetBytes(plainText);
#endif

// Convert the array of bytes into a BitArray.
BitArray bitArray;
if (utf8BOM)
{
// convert to bit array, leaving 24 bits for the UTF-8 preamble
var bitArray = ToBitArray(codeBytes, 24);
bitArray = ToBitArray(codeBytes, 24);
// write UTF8 preamble (EF BB BF) to the BitArray
DecToBin(0xEF, 8, bitArray, 0);
DecToBin(0xBB, 8, bitArray, 8);
DecToBin(0xBF, 8, bitArray, 16);
return bitArray;
}
else
{
return ToBitArray(codeBytes);
bitArray = ToBitArray(codeBytes);
}

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1
if (bufferFromPool != null)
ArrayPool<byte>.Shared.Return(bufferFromPool);
#endif

return bitArray;
}

/// <summary>
Expand Down