FDB2001: Value built with a Core factory in a transaction write
| Analyzer | FoundationDB.Client |
| Severity | Warning (performance) |
| Code fix | Yes |
Message
'{0}' allocates an intermediate buffer that the transaction copies again. Pass {1} instead.
Why
Slice.FromString, Encoding.UTF8.GetBytes, CrystalJson.ToSlice, and the other Core factories allocate a byte array, and the transaction then copies that array into its own buffer: one allocation per write, for nothing. The FdbValue encoders describe the value instead, and the transaction renders it straight into its buffer.
The rule reports the value argument of Set, SetVersionStampedValue, AtomicAdd, AtomicMax, and AtomicMin when it is one of the left-column expressions below, directly or through a local that this write alone uses. A Slice local shared by several writes keeps its buffer and is not reported.
| Value expression | Replacement |
|---|---|
Slice.FromString(s), Slice.FromStringUtf8(s), Slice.FromStringAscii(s), Encoding.UTF8.GetBytes(s) |
FdbValue.ToTextUtf8(s) |
Slice.FromFixed64(n) |
FdbValue.ToFixed64LittleEndian(n) |
Slice.FromGuid(g) |
FdbValue.ToUuid128(g) |
CrystalJson.ToSlice(obj), CrystalJson.ToBytes(obj) |
FdbValue.ToJson(obj) |
bytes.AsSpan(start, length).ToArray() |
FdbValue.ToBytes(bytes, start, length) |
Bad
tr.Set(subspace.Key("a"), Slice.FromString(json));
Good
tr.Set(subspace.Key("a"), FdbValue.ToTextUtf8(json));
Code fix
The fix rewrites the argument per the table, or the initializer of a local declared with var. A project that compiles against the netstandard2.0 build of the library has no FdbValue.ToUuid128, so Slice.FromGuid is reported there without a fix.
Suppress
#pragma warning disable FDB2001 // reason
or, for a whole project, in .editorconfig:
dotnet_diagnostic.FDB2001.severity = none
The whole performance tier can be muted at once:
dotnet_analyzer_diagnostic.category-FdbPerformance.severity = none