Skip to content

Commit 0b26a5f

Browse files
committed
优化动态命令生成对小片内存的过度消耗。 Ⓜ️
1 parent 396bbd8 commit 0b26a5f

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

Zongsoft.Core/src/Data/Metadata/DataCommandCollection.cs

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929

3030
using System;
3131
using System.Text;
32+
using System.Buffers;
3233
using System.Collections;
3334
using System.Collections.Generic;
3435

@@ -96,7 +97,7 @@ public IDataCommand Script(string driver, DataCommandMutability mutability, stri
9697
ArgumentException.ThrowIfNullOrEmpty(driver);
9798
ArgumentException.ThrowIfNullOrEmpty(script);
9899

99-
var key = $"#{Convert.ToHexString(System.Security.Cryptography.SHA1.HashData(Encoding.UTF8.GetBytes($"{driver.ToUpperInvariant()}:{script}")))}";
100+
var key = GetKey($"{driver.ToUpperInvariant()}:{script}");
100101

101102
return _dictionary.GetOrAdd(key, (key, argument) =>
102103
{
@@ -110,6 +111,38 @@ public IDataCommand Script(string driver, DataCommandMutability mutability, stri
110111

111112
return command;
112113
}, (driver, mutability, script, parameters));
114+
115+
static string GetKey(string text)
116+
{
117+
var count = Encoding.UTF8.GetMaxByteCount(text.Length);
118+
119+
if(count <= 1024)
120+
{
121+
Span<byte> data = stackalloc byte[count];
122+
var size = Encoding.UTF8.GetBytes(text, data);
123+
return Hash(data[.. size]);
124+
}
125+
126+
var bytes = ArrayPool<byte>.Shared.Rent(count);
127+
128+
try
129+
{
130+
var data = bytes.AsSpan(0, count);
131+
var size = Encoding.UTF8.GetBytes(text, data);
132+
return Hash(data[.. size]);
133+
}
134+
finally
135+
{
136+
ArrayPool<byte>.Shared.Return(bytes);
137+
}
138+
139+
static string Hash(ReadOnlySpan<byte> data)
140+
{
141+
Span<byte> code = stackalloc byte[System.Security.Cryptography.SHA1.HashSizeInBytes];
142+
System.Security.Cryptography.SHA1.HashData(data, code);
143+
return $"#{Convert.ToHexString(code)}";
144+
}
145+
}
113146
}
114147
#endregion
115148

Zongsoft.Core/src/Zongsoft.Core.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<Project Sdk="Microsoft.NET.Sdk">
22
<PropertyGroup>
3-
<Version>7.41.2</Version>
3+
<Version>7.41.3</Version>
44
<Product>Zongsoft Core Library</Product>
55
<Description>This is a core library about Zongsoft development framework.</Description>
66
<RootNamespace>Zongsoft</RootNamespace>

0 commit comments

Comments
 (0)