c# - 使用前缀、后缀和分隔符连接字符串的最快方法

标签 c# .net string

更新

正在关注 Mr Cheese's answer , 似乎是

public static string Join<T>(string separator, IEnumerable<T> values)

string.Join 的重载通过使用 StringBuilderCache 类获得了优势。

是否有人对此声明的正确性或原因有任何反馈?

我可以自己写吗,

public static string Join<T>(
    string separator,
    string prefix,
    string suffix,
    IEnumerable<T> values)

使用 StringBuilderCache 类的函数?


提交后my answer to this question我陷入了一些关于哪个是最佳答案的分析。

我在控制台 Program 类中编写了这段代码来测试我的想法。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

class Program
{
    static void Main()
    {
        const string delimiter = ",";
        const string prefix = "[";
        const string suffix = "]";
        const int iterations = 1000000;

        var sequence = Enumerable.Range(1, 10).ToList();

        Func<IEnumerable<int>, string, string, string, string>[] joiners =
            {
                Build,
                JoinFormat,
                JoinConcat
            };

        // Warmup
        foreach (var j in joiners)
        {
            Measure(j, sequence, delimiter, prefix, suffix, 5);
        }

        // Check
        foreach (var j in joiners)
        {
            Console.WriteLine(
                "{0} output:\"{1}\"",
                j.Method.Name,
                j(sequence, delimiter, prefix, suffix));
        }

        foreach (var result in joiners.Select(j => new
                {
                    j.Method.Name,
                    Ms = Measure(
                        j,
                        sequence,
                        delimiter,
                        prefix,
                        suffix,
                        iterations)
                }))
        {
            Console.WriteLine("{0} time = {1}ms", result.Name, result.Ms);
        }

        Console.ReadKey();
    }

    private static long Measure<T>(
        Func<IEnumerable<T>, string, string, string, string> func,
        ICollection<T> source,
        string delimiter,
        string prefix,
        string suffix,
        int iterations)
    {
        var stopwatch = new Stopwatch();

        stopwatch.Start();
        for (var i = 0; i < iterations; i++)
        {
            func(source, delimiter, prefix, suffix);
        }

        stopwatch.Stop();

        return stopwatch.ElapsedMilliseconds;
    }

    private static string JoinFormat<T>(
        IEnumerable<T> source,
        string delimiter,
        string prefix,
        string suffix)
    {
        return string.Format(
            "{0}{1}{2}",
            prefix,
            string.Join(delimiter, source),
            suffix);
    }

    private static string JoinConcat<T>(
        IEnumerable<T> source,
        string delimiter,
        string prefix,
        string suffix)
    {
        return string.Concat(
            prefix,
            string.Join(delimiter, source),
            suffix);
    }

    private static string Build<T>(
        IEnumerable<T> source,
        string delimiter,
        string prefix,
        string suffix)
    {
        var builder = new StringBuilder();
        builder = builder.Append(prefix);

        using (var e = source.GetEnumerator())
        {
            if (e.MoveNext())
            {
                builder.Append(e.Current);
            }

            while (e.MoveNext())
            {
                builder.Append(delimiter);
                builder.Append(e.Current);
            }
        }

        builder.Append(suffix);
        return builder.ToString();
    }
}

运行代码,在发布配置中,构建优化,从命令行我得到这样的输出。

...

Build time = 1555ms

JoinFormat time = 1715ms

JoinConcat time = 1452ms

这里(对我来说)唯一的惊喜是 Join-Format 组合是最慢的。经过考虑this answer ,这更有意义,string.Join 的输出由 string.Format 中的外部 StringBuilder 处理,有这种方法的固有延迟。

想来想去,我不是很清楚string.Join怎么可以更快。我读过它对 FastAllocateString() 的使用,但我不明白如何在不调用 .ToString() 的情况下准确地预分配缓冲区序列。为什么 Join-Concat 组合更快?

一旦我明白了这一点,是否有可能编写我自己的 unsafe string Join 函数,它采用额外的 prefixsuffix 参数并执行“安全”替代方案。

我已经进行了几次尝试,虽然它们起作用了,但它们并没有更快。

最佳答案

要尝试回答您最初的问题,我认为答案在于(令人惊叹的)Reflector 工具。您正在使用 IEnumerable 的对象集合,这也会导致调用 String.Join 方法中相同类型的重载。有趣的是,此函数与您的 Build 函数非常相似,因为它枚举集合并使用字符串生成器,这意味着它不需要提前知道所有字符串的长度。

public static string Join<T>(string separator, IEnumerable<T> values)
{

    if (values == null)
    {
        throw new ArgumentNullException("values");
    }
    if (separator == null)
    {
        separator = Empty;
    }
    using (IEnumerator<T> enumerator = values.GetEnumerator())
    {
        if (!enumerator.MoveNext())
        {
            return Empty;
        }
        StringBuilder sb = StringBuilderCache.Acquire(0x10);
        if (enumerator.Current != null)
        {
            string str = enumerator.Current.ToString();
            if (str != null)
            {
                sb.Append(str);
            }
        }
        while (enumerator.MoveNext())
        {
            sb.Append(separator);
            if (enumerator.Current != null)
            {
                string str2 = enumerator.Current.ToString();
                if (str2 != null)
                {
                    sb.Append(str2);
                }
            }
        }
        return StringBuilderCache.GetStringAndRelease(sb);
    }
}

它似乎在用缓存的 StringBuilder 做一些我不完全理解的事情,但这可能是它由于一些内部优化而变得更快的原因。当我在笔记本电脑上工作时,我可能之前已经被电源管理状态更改所困扰,所以我使用包含的“BuildCheat”方法(避免字符串生成器缓冲区容量加倍)重新运行代码并且时间非常接近String.Join(IEnumerable)(也在调试器之外运行)。

构建时间 = 1264 毫秒

JoinFormat = 1282ms

JoinConcat = 1108 毫秒

BuildCheat = 1166 毫秒

private static string BuildCheat<T>(
    IEnumerable<T> source,
    string delimiter,
    string prefix,
    string suffix)
{
    var builder = new StringBuilder(32);
    builder = builder.Append(prefix);

    using (var e = source.GetEnumerator())
    {
        if (e.MoveNext())
        {
            builder.Append(e.Current);
        }

        while (e.MoveNext())
        {
            builder.Append(delimiter);
            builder.Append(e.Current);
        }
    }

    builder.Append(suffix);
    return builder.ToString();
}

你问题的最后一部分的答案是你提到 FastAllocateString 的使用,但正如你所看到的,上面没有在传递 IEnumerable 的重载方法中调用它,它只在直接使用字符串时调用,而且绝对是在创建最终输出之前循环遍历字符串数组以求和它们的长度。

public static unsafe string Join(string separator, string[] value, int startIndex, int count)
{
    if (value == null)
    {
        throw new ArgumentNullException("value");
    }
    if (startIndex < 0)
    {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
    }
    if (count < 0)
    {
        throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
    }
    if (startIndex > (value.Length - count))
    {
        throw new ArgumentOutOfRangeException("startIndex", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
    }
    if (separator == null)
    {
        separator = Empty;
    }
    if (count == 0)
    {
        return Empty;
    }
    int length = 0;
    int num2 = (startIndex + count) - 1;
    for (int i = startIndex; i <= num2; i++)
    {
        if (value[i] != null)
        {
            length += value[i].Length;
        }
    }
    length += (count - 1) * separator.Length;
    if ((length < 0) || ((length + 1) < 0))
    {
        throw new OutOfMemoryException();
    }
    if (length == 0)
    {
        return Empty;
    }
    string str = FastAllocateString(length);
    fixed (char* chRef = &str.m_firstChar)
    {
        UnSafeCharBuffer buffer = new UnSafeCharBuffer(chRef, length);
        buffer.AppendString(value[startIndex]);
        for (int j = startIndex + 1; j <= num2; j++)
        {
            buffer.AppendString(separator);
            buffer.AppendString(value[j]);
        }
    }
    return str;
}

只是出于兴趣,我将您的程序更改为不使用泛型,并使 JoinFormat 和 JoinConcat 接受一个简单的字符串数组(我不能轻易更改 Build,因为它使用枚举器),因此 String.Join 使用上面的其他实现.结果非常令人印象深刻:

JoinFormat time = 386ms

JoinConcat 时间 = 226ms

也许您可以找到一种解决方案,既能充分利用快速字符串数组,又能使用通用输入...

关于c# - 使用前缀、后缀和分隔符连接字符串的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13419599/

相关文章:

c# - 动态 where 子句 Entity Framework 3.5

c# - 传递给操作结果时如何绑定(bind)可变数量的列表项

Ruby 帖子标题 slug

python - 对 Python 列表中的每个元素执行字符串操作

java - 如何使用递归循环从 char[] 数组返回字符串。(java)

c# - 系统.DllNotFoundException : Unable to load DLL 'SqlServerSpatial110.dll' : The specified module could not be found

c# - Restsharp XML 请求

c# - 字符串数组未正确序列化为 json?

c# - XML-RPC.NET 和 C# 动态类型

c# - .NET Compact Framework 中的 LINQ to SQL 替换