gpt4 book ai didi

c# - StartsWith 应该只用于订购吗?

转载 作者:可可西里 更新时间:2023-11-01 08:49:26 26 4
gpt4 key购买 nike

我正在阅读 Microsoft 的 Best Practices for Using Strings in the .NET Framework .

它给出了以下示例作为对 StringComparison.OrdinalIgnoreCase 的介绍:

public static bool IsFileURI(string path) 
{
return path.StartsWith("FILE:", StringComparison.OrdinalIgnoreCase);
}

到目前为止,还不错。但它接着说:

However, the preceding example uses the String.StartsWith(String, StringComparison) method to test for equality. Because the purpose of the comparison is to test for equality instead of ordering the strings, a better alternative is to call the Equals method, as shown in the following example.

public static bool IsFileURI(string path)
{
if (path.Length < 5) return false;

return String.Equals(path.Substring(0, 5), "FILE:",
StringComparison.OrdinalIgnoreCase);
}

我正在努力了解为什么第二个版本更好。我可以理解从 CompareTo(比较)切换到 Equals(相等),但是 StartsWith 不也是一个相等测试吗?我是否遗漏了什么或者这是一个文档错误?

最佳答案

不是真正的答案,但 StartsWith() 是一个相等性测试,我认为这是一个文档错误,但我很想知道性能,所以我做了使用以下代码的基准:

class Program {
static void Main( string[ ] args ) {
Stopwatch sw = Stopwatch.StartNew( );
for ( int i = 0; i < 1000000000; i++ ) //1 billion times
IsFileURI1( "File:\\ThisIsATest" );
sw.Stop( );
Console.WriteLine( "String.StartsWith(): " + sw.ElapsedMilliseconds.ToString( ) );

sw.Restart( );
for ( int i = 0; i < 1000000000; i++ ) //1 billion times
IsFileURI2( "File:\\ThisIsATest" );
sw.Stop( );
Console.WriteLine( "String.Equals(): " + sw.ElapsedMilliseconds.ToString( ) );
}

public static bool IsFileURI1( string path ) {
return path.StartsWith( "FILE:", StringComparison.OrdinalIgnoreCase );
}

public static bool IsFileURI2( string path ) {
if ( path.Length < 5 ) return false;

return String.Equals( path.Substring( 0, 5 ), "FILE:", StringComparison.OrdinalIgnoreCase );
}
}

结果是(毫秒):

String.StartsWith(): 90102 
String.Equals(): 73113

因此,就性能而言,第二种解决方案更好,而且快 20%

关于c# - StartsWith 应该只用于订购吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12680282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com