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

Avoid linear scan operation on large strings. #402

Merged
merged 2 commits into from
Feb 12, 2021
Merged
Changes from all commits
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
17 changes: 10 additions & 7 deletions src/SQLitePCLRaw.core/raw.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1125,14 +1125,18 @@ static public int sqlite3_bind_text(sqlite3_stmt stmt, int index, utf8z val)

static public int sqlite3_bind_text(sqlite3_stmt stmt, int index, string val)
{
if (val != null)
const int OptimizedLengthThreshold = 512;

// stackalloc the conversion to bytes for small strings to help avoid unnecessary GC pressure. This is
// ultimately safe as we pass the SQLITE_TRANSIENT (https://www.sqlite.org/c3ref/c_static.html) flag to
// sqlite, which causes them to create their own copy.

// Don't bother doing the linear GetByteCount check for strings that are certainly too large to fit within
// our byte count threshold.
if (val != null && val.Length <= OptimizedLengthThreshold)
{
// stackalloc the conversion to bytes for small strings to help avoid unnecessary GC
// pressure. This is ultimately safe as we pass the SQLITE_TRANSIENT
// (https://www.sqlite.org/c3ref/c_static.html) flag to sqlite, which causes them to
// create their own copy.
var utf8ByteCount = Encoding.UTF8.GetByteCount(val);
if ((utf8ByteCount <= 512) && (utf8ByteCount > 0))
if ((utf8ByteCount <= OptimizedLengthThreshold) && (utf8ByteCount > 0))
{
Span<byte> bytes = stackalloc byte[utf8ByteCount];
unsafe
Expand Down Expand Up @@ -1381,4 +1385,3 @@ static public int sqlite3_keyword_name(int i, out string name)
}
}
}