慎用ToLower和ToUpper,小心把你的系统给拖垮了

元数据

作者: 编辑推荐:
标题: 慎用ToLower和ToUpper,小心把你的系统给拖垮了
分类: #dotnet
地址: https://www.cnblogs.com/huangxincheng/archive/2020/05/04/12827314.html

笔记

string.Compare 跳转

使用 Ignore 来忽略大小写

string.Compare(i.TradeFrom, tradefrom, StringComparison.OrdinalIgnoreCase)
为什么ToLower,ToUpper会有如此大的影响 跳转

0:000> !dumpheap -type System.String -stat
Statistics:
MT Count TotalSize Class Name
00007ff8e7a9a120 1 24 System.Collections.Generic.GenericEqualityComparer`1[[System.String, mscorlib]]
00007ff8e7a99e98 1 80 System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Globalization.CultureData, mscorlib]]
00007ff8e7a9a378 1 96 System.Collections.Generic.Dictionary`2+Entry[[System.String, mscorlib],[System.Globalization.CultureData, mscorlib]][]
00007ff8e7a93200 19 2264 System.String[]
00007ff8e7a959c0 429 17894 System.String
Total 451 object

可以看到托管堆上有Count=429个string对象,那这个429怎么来的? 组成:短文128个,ToUpper后128个,系统默认165个,query字符串2个,不明字符串6个,最后就是128 +128 + 165 + 2 + 6=429

string.Compare解析 跳转

[SecuritySafeCritical]
private unsafe static int CompareOrdinalIgnoreCaseHelper(string strA, string strB)
{
int num = Math.Min(strA.Length, strB.Length);
fixed (char* ptr = &strA.m_firstChar)
{
fixed (char* ptr2 = &strB.m_firstChar)
{
char* ptr3 = ptr;
char* ptr4 = ptr2;
while (num != 0)
{
int num2 = (int)(*ptr3);
int num3 = (int)(*ptr4); 
if (num2 - 97 <= 25)
{
num2 -= 32;
}
if (num3 - 97 <= 25)
{
num3 -= 32;
}
if (num2 != num3)
{
return num2 - num3;
}
ptr3++;
ptr4++;
num--;
}
return strA.Length - strB.Length;
}
}
}