Skip to content

Commit

Permalink
Microsoft.Data.Sqlite: Use Span overload of sqlite3_prepare
Browse files Browse the repository at this point in the history
Removes a lot of unnecessary allocations and conversions from utf8

Fixes #16202
  • Loading branch information
bricelam committed Mar 8, 2021
1 parent bcc1fe8 commit 063a2bd
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/Microsoft.Data.Sqlite.Core/SqliteCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Sqlite.Properties;
Expand Down Expand Up @@ -470,15 +471,19 @@ private IEnumerable<sqlite3_stmt> PrepareAndEnumerateStatements(Stopwatch timer)
{
DisposePreparedStatements(disposing: false);

var byteCount = Encoding.UTF8.GetByteCount(_commandText);
var sql = new byte[byteCount + 1];
Encoding.UTF8.GetBytes(_commandText, 0, _commandText.Length, sql, 0);

int rc;
sqlite3_stmt stmt;
var tail = _commandText;
var start = 0;
do
{
timer.Start();

string nextTail;
while (IsBusy(rc = sqlite3_prepare_v2(_connection!.Handle, tail, out stmt, out nextTail)))
ReadOnlySpan<byte> tail;
while (IsBusy(rc = sqlite3_prepare_v2(_connection!.Handle, sql.AsSpan(start), out stmt, out tail)))
{
if (CommandTimeout != 0
&& timer.ElapsedMilliseconds >= CommandTimeout * 1000L)
Expand All @@ -490,14 +495,14 @@ private IEnumerable<sqlite3_stmt> PrepareAndEnumerateStatements(Stopwatch timer)
}

timer.Stop();
tail = nextTail;
start = sql.Length - tail.Length;

SqliteException.ThrowExceptionForRC(rc, _connection.Handle);

// Statement was empty, white space, or a comment
if (stmt.IsInvalid)
{
if (tail.Length != 0)
if (start < byteCount)
{
continue;
}
Expand All @@ -509,7 +514,7 @@ private IEnumerable<sqlite3_stmt> PrepareAndEnumerateStatements(Stopwatch timer)

yield return stmt;
}
while (tail.Length != 0);
while (start < byteCount);

_prepared = true;
}
Expand Down

0 comments on commit 063a2bd

Please sign in to comment.