-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathDistributedCacheBenchmarks.cs
234 lines (207 loc) · 7.54 KB
/
DistributedCacheBenchmarks.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Linq;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
namespace Microsoft.Extensions.Caching.Benchmarks;
[MemoryDiagnoser, ShortRunJob]
public class DistributedCacheBenchmarks : IDisposable
{
private readonly IBufferDistributedCache sqlServer, redis;
private readonly ConnectionMultiplexer multiplexer;
private readonly Random random = new Random();
private readonly string[] keys;
private readonly Task<byte[]?>[] pendingBlobs = new Task<byte[]?>[OperationsPerInvoke];
// create a local DB named CacheBench, then
// dotnet tool install --global dotnet-sql-cache
// dotnet sql-cache create "Data Source=.;Initial Catalog=CacheBench;Integrated Security=True;Trust Server Certificate=True" dbo BenchmarkCache
private const string SqlServerConnectionString = "Data Source=.;Initial Catalog=CacheBench;Integrated Security=True;Trust Server Certificate=True";
private const string RedisConfigurationString = "127.0.0.1,AllowAdmin=true";
public const int OperationsPerInvoke = 256;
public void Dispose()
{
(sqlServer as IDisposable)?.Dispose();
(redis as IDisposable)?.Dispose();
multiplexer.Dispose();
}
public enum BackendType
{
Redis,
SqlServer,
}
[Params(BackendType.Redis, BackendType.SqlServer)]
public BackendType Backend { get; set; } = BackendType.Redis;
private IBufferDistributedCache _backend = null!;
public DistributedCacheBenchmarks()
{
var services = new ServiceCollection();
services.AddDistributedSqlServerCache(options =>
{
options.TableName = "BenchmarkCache";
options.SchemaName = "dbo";
options.ConnectionString = SqlServerConnectionString;
});
sqlServer = (IBufferDistributedCache)services.BuildServiceProvider().GetRequiredService<IDistributedCache>();
multiplexer = ConnectionMultiplexer.Connect(RedisConfigurationString);
services = new ServiceCollection();
services.AddStackExchangeRedisCache(options =>
{
options.ConnectionMultiplexerFactory = () => Task.FromResult<IConnectionMultiplexer>(multiplexer);
});
redis = (IBufferDistributedCache)services.BuildServiceProvider().GetRequiredService<IDistributedCache>();
keys = new string[10000];
for (int i = 0; i < keys.Length; i++)
{
keys[i] = Guid.NewGuid().ToString();
}
}
[GlobalSetup]
public void GlobalSetup()
{
// reset
_backend = Backend switch
{
BackendType.Redis => redis,
BackendType.SqlServer => sqlServer,
_ => throw new ArgumentOutOfRangeException(nameof(Backend)),
};
_backend.Get(new Guid().ToString()); // just to touch it first
switch (Backend)
{
case BackendType.SqlServer:
using (var conn = new SqlConnection(SqlServerConnectionString))
{
using var cmd = conn.CreateCommand();
cmd.CommandText = "truncate table dbo.BenchmarkCache";
conn.Open();
cmd.ExecuteNonQuery();
}
break;
case BackendType.Redis:
using (var multiplexer = ConnectionMultiplexer.Connect(RedisConfigurationString))
{
multiplexer.GetServer(multiplexer.GetEndPoints().Single()).FlushDatabase();
}
break;
}
var options = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30) };
options.SlidingExpiration = Sliding ? TimeSpan.FromMinutes(5) : null;
var value = new byte[PayloadSize];
foreach (var key in keys)
{
random.NextBytes(value);
_backend.Set(key, value, options);
}
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public int GetSingleRandom()
{
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += _backend.Get(RandomKey())?.Length ?? 0;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public int GetConcurrentRandom()
{
Func<Task<byte[]?>> callback = () => _backend.GetAsync(RandomKey());
for (int i = 0; i < OperationsPerInvoke; i++)
{
pendingBlobs[i] = Task.Run(callback);
}
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += (pendingBlobs[i].Result)?.Length ?? 0;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public async Task<int> GetSingleRandomAsync()
{
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += (await _backend.GetAsync(RandomKey()))?.Length ?? 0;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public async Task<int> GetConcurrentRandomAsync()
{
Func<Task<byte[]?>> callback = () => _backend.GetAsync(RandomKey());
for (int i = 0; i < OperationsPerInvoke; i++)
{
pendingBlobs[i] = Task.Run(callback);
}
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += (await pendingBlobs[i])?.Length ?? 0;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public int GetSingleFixed()
{
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += _backend.Get(FixedKey())?.Length ?? 0;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public int GetConcurrentFixed()
{
Func<Task<byte[]?>> callback = () => _backend.GetAsync(FixedKey());
for (int i = 0; i < OperationsPerInvoke; i++)
{
pendingBlobs[i] = Task.Run(callback);
}
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += (pendingBlobs[i].Result)?.Length ?? 0;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public async Task<int> GetSingleFixedAsync()
{
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += (await _backend.GetAsync(FixedKey()))?.Length ?? 0;
}
return total;
}
[Benchmark(OperationsPerInvoke = OperationsPerInvoke)]
public async Task<int> GetConcurrentFixedAsync()
{
Func<Task<byte[]?>> callback = () => _backend.GetAsync(FixedKey());
for (int i = 0; i < OperationsPerInvoke; i++)
{
pendingBlobs[i] = Task.Run(callback);
}
int total = 0;
for (int i = 0; i < OperationsPerInvoke; i++)
{
total += (await pendingBlobs[i])?.Length ?? 0;
}
return total;
}
private string FixedKey() => keys[42];
private string RandomKey() => keys[random.Next(keys.Length)];
[Params(1024, 128, 10 * 1024)]
public int PayloadSize { get; set; } = 1024;
[Params(true, false)]
public bool Sliding { get; set; } = true;
}