c# - .NET 如何准确比较字符串?
问题描述
字符串比较是如何工作的?-这是我想知道一段时间的事情。
- C# 在检查每个字符之前是否检查每个字符串的长度?
- 或者它是否开始循环并首先单独比较每个字符?
- 即使一个字符不同,它会继续检查每个字符,还是在发现一个字符不同后停止?
- 或者它甚至不直接循环遍历每个字符?
我知道这是一堆非常开放的问题,但我无法找到任何答案。
任何答案以及文档都将受到赞赏。干杯!
解决方案
基于此https://referencesource.microsoft.com/#mscorlib/system/string.cs,11648d2d83718c5e。是的,它确实首先检查长度。
// Determines whether two strings match.
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
public override bool Equals(Object obj) {
if (this == null) //this is necessary to guard against reverse-pinvokes and
throw new NullReferenceException(); //other callers who do not use the callvirt instruction
String str = obj as String;
if (str == null)
return false;
if (Object.ReferenceEquals(this, obj))
return true;
if (this.Length != str.Length)
return false;
return EqualsHelper(this, str);
}
[System.Security.SecuritySafeCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
private unsafe static bool EqualsHelper(String strA, String strB)
{
Contract.Requires(strA != null);
Contract.Requires(strB != null);
Contract.Requires(strA.Length == strB.Length);
int length = strA.Length;
fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar)
{
char* a = ap;
char* b = bp;
// unroll the loop
#if AMD64
// for AMD64 bit platform we unroll by 12 and
// check 3 qword at a time. This is less code
// than the 32 bit case and is shorter
// pathlength
while (length >= 12)
{
if (*(long*)a != *(long*)b) return false;
if (*(long*)(a+4) != *(long*)(b+4)) return false;
if (*(long*)(a+8) != *(long*)(b+8)) return false;
a += 12; b += 12; length -= 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) return false;
if (*(int*)(a+2) != *(int*)(b+2)) return false;
if (*(int*)(a+4) != *(int*)(b+4)) return false;
if (*(int*)(a+6) != *(int*)(b+6)) return false;
if (*(int*)(a+8) != *(int*)(b+8)) return false;
a += 10; b += 10; length -= 10;
}
#endif
// This depends on the fact that the String objects are
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
while (length > 0)
{
if (*(int*)a != *(int*)b) break;
a += 2; b += 2; length -= 2;
}
return (length <= 0);
}
}
推荐阅读
- java - Spring Security 总是返回 Postman 中禁止的 403
- automation - Cypress - supportFile 中的 before() 钩子在每个规范之前运行
- c# - 单元测试 EF Core 3.1 异步方法
- django - 在 AWS 上运行 Django REST-API - apache 服务器什么都不做
- r - 从包含R中每行列表中的列表的数据帧的每一行中提取一个参数
- .net - Azure Service Bus: Microsoft.Azure.WebJobs.Script.HostDisposedException: The host is disposed and cannot be used
- mqtt - MQTT 订阅是否对非干净连接具有幂等性
- javascript - JavaScript - 表单提交上的 beforeunload 覆盖
- python - 我无法在 Flask-admin 中更改 is_accessible
- c - C 中带有回调函数的异步 I/O —— I/O 线程究竟何时以及如何返回?