Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# C中字符串类型的最快(内置)比较是什么#_C#_Performance_String - Fatal编程技术网

C# C中字符串类型的最快(内置)比较是什么#

C# C中字符串类型的最快(内置)比较是什么#,c#,performance,string,C#,Performance,String,对于C#中的字符串类型,最快的内置比较方法是什么?我不介意排版/语义含义:目的是在排序列表中使用比较器,以便在大型集合中快速搜索。我认为只有两种方法:Compare和CompareOrdinal。最快的是什么 另外,有没有一种更快的方法来进行字符串比较?我假设您想要的是小于/等于/大于的比较,而不仅仅是相等;平等是一个稍有不同的话题,尽管原则基本相同。如果你只在“ >排序列表> /代码>中搜索存在,我会考虑使用字典 -你真的需要所有排序吗? String.CompareOrdinal,或使用允许

对于C#中的字符串类型,最快的内置比较方法是什么?我不介意排版/语义含义:目的是在排序列表中使用比较器,以便在大型集合中快速搜索。我认为只有两种方法:
Compare
CompareOrdinal
。最快的是什么


另外,有没有一种更快的方法来进行字符串比较?

我假设您想要的是小于/等于/大于的比较,而不仅仅是相等;平等是一个稍有不同的话题,尽管原则基本相同。如果你只在“<代码> >排序列表> /代码>中搜索存在,我会考虑使用<代码>字典<代码> -你真的需要所有排序吗?

String.CompareOrdinal
,或使用允许提供比较的
String.Compare
重载,并指定序号(区分大小写)比较,例如
String.Compare(x,y,stringcomparation.ordinal)
将是最快的

基本上,顺序比较只需逐个字符遍历两个字符串,直到找到差异。如果没有发现任何差异,且长度相同,则结果为0。如果未发现任何差异,但长度不相同,则较长的字符串被视为“较大”。如果它确实发现了差异,它可以根据顺序中哪个字符“大”,立即计算出哪个字符被视为“大”

换句话说,这就像在两个
char[]
值之间进行明显的比较


对文化敏感的比较必须执行各种曲折的壮举,这取决于你使用的确切文化。有关此示例,请参见。很明显,遵循更复杂的规则会使这一过程变得更慢。

最快的是带引用相等性测试的内部字符串,但您只能进行相等性测试,而且这是以大量内存为代价的-非常昂贵,几乎从来都不是推荐的课程

除此之外,区分大小写的顺序测试将是最快的,对于非区域性特定的字符串,绝对建议使用此方法。如果它适用于您的用例,则区分大小写的速度更快

指定
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase
时,字符串比较将是非语言的。也就是说,在做出比较决策时,会忽略特定于自然语言的特性。这意味着决策基于简单的字节比较,忽略由区域性参数化的大小写或等价表因此,通过显式地将参数设置为
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase
,您的代码通常会提高速度,提高正确性,并变得更可靠


我使用秒表检查了string.Compare和string.CompareOrdinal

    --Compare Ordinal  case 1 
    Stopwatch sw = new Stopwatch();
    sw.Start();
    int x = string.CompareOrdinal("Jaswant Agarwal", "Jaswant Agarwal");
    sw.Stop();
    lblTimeGap.Text = sw.Elapsed.ToString(); 






    -- Only compare  case 2
    Stopwatch sw = new Stopwatch();
    sw.Start();
    int x = string.Compare("Jaswant Agarwal", "Jaswant Agarwal");
    sw.Stop();
    lblTimeGap.Text = sw.Elapsed.ToString();
在案例1中,平均运行时间为00:00:00.000030 在案例2中,平均运行时间为00:00:00.0000086

我尝试了不同的相等和不相等字符串组合,发现每次CompareOrdinal都比只比较快


这是我自己的观察结果。您也可以尝试在表单上放置两个按钮,然后在重新分级事件中复制粘贴此代码

我设计了一个单元测试,使用本文提到的一些方法测试字符串比较速度。此测试是使用.NET4运行的

简而言之,没有太大的差异,我不得不进行100000000次迭代才能看到显著的差异。由于似乎要依次比较字符,直到发现差异,因此字符串的相似性不可避免地起到了一定作用

这些结果实际上似乎表明使用str1.Equals(str2)是比较字符串的最快方法。

这些是测试结果,测试类别包括:

######## SET 1 compared strings are the same: 0
#### Basic == compare: 413
#### Equals compare: 355
#### Equals(compare2, StringComparison.Ordinal) compare: 387
#### String.Compare(compare1, compare2, StringComparison.Ordinal) compare: 426
#### String.CompareOrdinal(compare1, compare2) compare: 412

######## SET 2 compared strings are NOT the same: 0
#### Basic == compare: 710
#### Equals compare: 733
#### Equals(compare2, StringComparison.Ordinal) compare: 840
#### String.Compare(compare1, compare2, StringComparison.Ordinal) compare: 987
#### String.CompareOrdinal(compare1, compare2) compare: 776

using System;
using System.Diagnostics;
using NUnit.Framework;

namespace Fwr.UnitTests
{
    [TestFixture]
    public class StringTests
    {
        [Test]
        public void Test_fast_string_compare()
        {
            int iterations = 100000000;
            bool result = false;
            var stopWatch = new Stopwatch();

            Debug.WriteLine("######## SET 1 compared strings are the same: " + stopWatch.ElapsedMilliseconds);

            string compare1 = "xxxxxxxxxxxxxxxxxx";
            string compare2 = "xxxxxxxxxxxxxxxxxx";

            // Test 1

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = compare1 == compare2;
            }

            stopWatch.Stop();

            Debug.WriteLine("#### Basic == compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 2

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = compare1.Equals(compare2);
            }

            stopWatch.Stop();

            Debug.WriteLine("#### Equals compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 3

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = compare1.Equals(compare2, StringComparison.Ordinal);
            }

            stopWatch.Stop();

            Debug.WriteLine("#### Equals(compare2, StringComparison.Ordinal) compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 4

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = String.Compare(compare1, compare2, StringComparison.Ordinal) != 0;
            }

            stopWatch.Stop();

            Debug.WriteLine("#### String.Compare(compare1, compare2, StringComparison.Ordinal) compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 5

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = String.CompareOrdinal(compare1, compare2) != 0;
            }

            stopWatch.Stop();

            Debug.WriteLine("#### String.CompareOrdinal(compare1, compare2) compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            Debug.WriteLine("######## SET 2 compared strings are NOT the same: " + stopWatch.ElapsedMilliseconds);

            compare1 = "ueoqwwnsdlkskjsowy";
            compare2 = "sakjdjsjahsdhsjdak";

            // Test 1

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = compare1 == compare2;
            }

            stopWatch.Stop();

            Debug.WriteLine("#### Basic == compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 2

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = compare1.Equals(compare2);
            }

            stopWatch.Stop();

            Debug.WriteLine("#### Equals compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 3

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = compare1.Equals(compare2, StringComparison.Ordinal);
            }

            stopWatch.Stop();

            Debug.WriteLine("#### Equals(compare2, StringComparison.Ordinal) compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 4

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = String.Compare(compare1, compare2, StringComparison.Ordinal) != 0;
            }

            stopWatch.Stop();

            Debug.WriteLine("#### String.Compare(compare1, compare2, StringComparison.Ordinal) compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();

            // Test 5

            stopWatch.Start();

            for (int i = 0; i < iterations; i++)
            {
                result = String.CompareOrdinal(compare1, compare2) != 0;
            }

            stopWatch.Stop();

            Debug.WriteLine("#### String.CompareOrdinal(compare1, compare2) compare: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Reset();
        }
    }
}
集1比较的字符串相同:0
####基本==比较:413
####相等比较:355
####等于(compare2,stringcomparation.Ordinal)比较:387
####String.Compare(compare1、compare2、stringcomparation.Ordinal)Compare:426
####String.CompareOrdinal(compare1,compare2)compare:412
########集合2比较的字符串不相同:0
####基本==比较:710
####相等比较:733
####等于(compare2,stringcomparation.Ordinal)比较:840
####String.Compare(compare1、compare2、stringcomparation.Ordinal)Compare:987
####String.CompareOrdinal(compare1,compare2)compare:776
使用制度;
使用系统诊断;
使用NUnit.Framework;
命名空间Fwr.UnitTests
{
[测试夹具]
公共类StringTests
{
[测试]
公共无效测试\u快速\u字符串\u比较()
{
整数迭代次数=100000000;
布尔结果=假;
var stopWatch=新秒表();
Debug.WriteLine(“+stopWatch.ElapsedMilliseconds”);
字符串compare1=“xxxxxxxxxxxxxxxx”;
字符串compare2=“xxxxxxxxxxxxxxxx”;
//测试1
秒表。开始();
对于(int i=0;iIf strA.length = strB.length then
   if string.compare(strA,strB,true) = 0 then
      TheyAreEqual
   End if
End if
if(strA.Length == strB.Length)
{
   if(string.Compare(strA,strB,true) == 0)
   {
       //they are equal
   }
}
public bool StringsMatch(string string1, string string2)
{
    if (string1 == null && string2 == null) return true;
    return string1.Equals(string2, StringComparison.Ordinal);
}
public bool StringsMatch(string string1, string string2)
{
    if (string1 == null && string2 == null) return true;
    return string.CompareOrdinal(string1, string2) == 0 ? true : false;
}
[Test]
public void StringsMatch_OnlyString1NullOrEmpty_ReturnFalse()
{
    Authentication auth = new Authentication();
    Assert.IsFalse(auth.StringsMatch(null, "foo"));
    Assert.IsFalse(auth.StringsMatch("", "foo"));
}