Skip to content

Commit

Permalink
Merge pull request #402 from CyrusNajmabadi/thresholdLength
Browse files Browse the repository at this point in the history
Avoid linear scan operation on large strings.
  • Loading branch information
ericsink authored Feb 12, 2021
2 parents f2998ed + 0558234 commit 6027df0
Showing 1 changed file with 10 additions and 7 deletions.
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)
}
}
}

0 comments on commit 6027df0

Please sign in to comment.