dotnet / dotnet/efcore

TagWith using formattable string takes disproportionately much time

Open
#32,622 19 comments 0 reactions 0 assignees View on GitHub
area-query customer-reported
Dominant language
C#
Stars
14.8k
Forks
3.4k
PR merge metrics
PR metrics pending

Description

When using a formattable string in `TagWith`, performance drops dramatically.

This code that queries a table a 1000 times demonstrates the effect of formattable strings:

```c#
var ids = Plots.Take(1000).Select(p => p.PlotId).ToList();

var sw = Stopwatch.StartNew();
foreach (var id in ids)
{
var plot = Plots.TagWith("Plots selected plot xxxxxx").First(p => p.PlotId == id);
}
var e1 = sw.Elapsed;

sw.Restart();
foreach (var id in ids)
{
var plot = Plots.TagWith($"Plots selected plot {id}").First(p => p.PlotId == id);
}
var e2 = sw.Elapsed;

sw.Restart();
foreach (var id in ids)
{
var plot = Plots.TagWith($"Plots selected plot {id}").First(p => p.PlotId == id);
}
var e3 = sw.Elapsed;

sw.Restart();
foreach (var id in ids)
{
var plot = Plots.TagWith("Plots selected plot xxxxxx").First(p => p.PlotId == id);
}
var e4 = sw.Elapsed;

e1.Dump("No tags");
e2.Dump("Tags");
e3.Dump("Tags");
e4.Dump("No tags");
```

The result:

```
No tags
00:00:00.2720288
Tags
00:00:04.6038496
Tags
00:00:05.9300289
No tags
00:00:00.2160600
```

The result when only generating the strings used in the tags:

```
No tags
00:00:00.0000031
Tags
00:00:00.0000509
Tags
00:00:00.0000499
No tags
00:00:00.0000029
```

Clearly the time added in queries with formattable strings in tags is far more than the overhead of string interpolation.

Strangely enough, first creating the string (`var s = $"Plots selected plot {id}".ToString();`) and putting it in the tag does not make a difference. What's going on here?

FYI: `PlotId` is an `int`, the highest value here is `134647`.

EF Core version: 7.13
Database provider: Microsoft.EntityFrameworkCore.SqlServer 2019
Target framework: NET 6.0
Operating system: win11
IDE: Visual Studio 2022/Linqpad 7

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.