String+ String.Concat String.Format StringBuilder 之间的性能测试

找到一篇国外的代码,专门来测试这个,

String+

String.Concat

String.Format

StringBuilder

前三个在100个左右字符串差不多,

String.Concat会获得稍微好一点点的性能提高,

String.Format会让你使用起来更方便,

StringBuilder更适合更多更长的字符串拼接,

如果有其它见解,还请指导。

using System;
using System.Diagnostics;
using System.Text;
namespace CompareInstructionExecutionSpeed
{
    public delegate void CompareExcecutionSpeed(int loop);
    class Program
    {
        public static string ResultConcatenation = string.Empty;
        public static readonly StringBuilder Sb = new StringBuilder();
        public static readonly Stopwatch Stopwatch = new Stopwatch();

        public static void Main()
        {
            CompareExcecutionSpeed methods = StringBuilderExecutionSpeed;
            methods += StringConcatExecutionSpeed;
            methods += ManualConcatenationExecutionSpeed;
            methods += StringFormatExecutionSpeed;
            //methods+=Some Method -- you can add your method to calculate speed.

            methods.Invoke(100);//count

            Console.ReadKey();
        }

        //Elapsing StringBuilder -------------------------------------------
        public static void StringBuilderExecutionSpeed(int loop)
        {
            Stopwatch.Restart();
            for (int i = 0; i < loop; i++)
            {
                ShowPercentProgress(i, loop);
                Sb.Append(" str");
                Sb.AppendLine(i.ToString());
            }
            Stopwatch.Stop();
            ShowCompareResult("StringBuilder", Stopwatch);
        }

        //Elapsing Str1+Str2+... -------------------------------------------
        public static void ManualConcatenationExecutionSpeed(int loop)
        {
            Stopwatch.Restart();
            for (int i = 0; i < loop; i++)
            {
                ShowPercentProgress(i, loop);
                ResultConcatenation += " str" + i + "\n";
            }
            Stopwatch.Stop();
            ShowCompareResult("str1+str2+...", Stopwatch);
        }

        //Elapsing String.Concat -------------------------------------------
        public static void StringConcatExecutionSpeed(int loop)
        {
            Stopwatch.Restart();
            for (int i = 0; i < loop; i++)
            {
                ShowPercentProgress(i, loop);
                ResultConcatenation += string.Concat(" str", i, "\n");
            }
            Stopwatch.Stop();
            ShowCompareResult("String.Concat", Stopwatch);

        }

        //Elapsing String.Format -------------------------------------------
        public static void StringFormatExecutionSpeed(int loop)
        {
            Stopwatch.Restart();
            for (int i = 0; i < loop; i++)
            {
                ShowPercentProgress(i, loop);
                ResultConcatenation += string.Format(" str{0}\n", i);
            }
            Stopwatch.Stop();
            ShowCompareResult("String.Format", Stopwatch);
        }

        //Show Compare Result---------------------------------------------
        public static void ShowCompareResult(string message, Stopwatch stopwatch)
        {
            Console.ResetColor();
            Console.WriteLine("\r{0}\t{1,9} Millisecond  ~={2,3} second  ~={3,3} minutes",
                message,
                Math.Round(stopwatch.Elapsed.TotalMilliseconds),
                Math.Round(stopwatch.Elapsed.TotalSeconds),
                Math.Round(stopwatch.Elapsed.TotalMinutes));
        }

        //Show processing progress----------------------------------------
        static void ShowPercentProgress(int currElementIndex, int totalElementCount)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            int percent = (100 * (currElementIndex + 1)) / totalElementCount;
            Console.Write("\r{0}%", percent);
        }
    }
}
时间: 2024-08-26 22:38:09

String+ String.Concat String.Format StringBuilder 之间的性能测试的相关文章

String、StringBuffer、StringBuilder之间区别

String,StringBuffer,StringBuilder 之间区别 在字符串处理中C#提供了String.StringBuffer.StringBuilder三个类.那么他们到底有什么优缺点,到底什么时候该用谁呢?下面我们从以下几点说明一下: 1.  三者在执行速度方面的比较:StringBuilder >StringBuffer > String String一旦赋值或实例化后就不可更改,如果赋予新值将会重新开辟内存地址进行存储.而StringBuffer类使用append和ins

Java的——String类、StringBuffer和StringBuilder、不可变和可变字符序列使用陷阱

Java的知识点21--String类.StringBuffer和StringBuilder.不可变和可变字符序列使用陷阱 原文链接 https://blog.csdn.net/qq_39368007/article/details/84033272 String类 String 类对象代表不可变的Unicode字符序列,因此我们可以将String对象称为"不可变对象" substring()是对字符串的截取操作,但本质是读取原字符串内容生成了新的字符串. String测试代码 pac

string.Join和string.Concat的区别

源自Difference between String.Join() vs String.Concat() With .NET 4.0, String.Join() uses StringBuilder class internally so it is more efficient.Whereas String.Concat() uses basic concatenation of String using "+" which is of course not an efficie

java基础----&gt;String和MessageFormat的format方法

这里介绍一下String和MessageFormat中的format方法的差异以及实现原理. String与MessageFormat的说明 一.两者的使用场景 String.format:for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. MessageFormat.format:to produce

Java String字符串/==和equals区别,str。toCharAt(),getBytes,indexOf过滤存在字符,trim()/String与StringBuffer多线程安全/StringBuilder单线程—— 14.0

课程概要 String 字符串 String字符串常用方法 StringBuffer StringBuilder String字符串: 1.实例化String对象 直接赋值  String str="Hello";  推荐这种 使用关键字new  String str1=new String("Hello"); 在内存中开辟2个空间 如图: 源代码 StringDemo01.java 2.String内容的比较 String str="Hello"

Android studio2.2 ndk 错误 :format not a string literal and no format arguments!

在Android Studio2.2 进行NDK编程,在对*char 字符串 进行日志输出时,报错: error: format not a string literal and no format arguments [-Werror=format-security] 代码: 网上说是版本不兼容导致的!搜索了下解决 方法如下: 解决方法: 在你的ndk目录下修改build/core/default-build-commands.mk TARGET_FORMAT_STRING_CFLAGS :=

format not a string literal and no format arguments

今天cocos2d-x打包 android的时候报错:format not a string literal and no format arguments 报错点是:__String::createWithFormat(s_szFuWenEffect2[GetType()])->getCString() 代码vs2015编译是通过的,没任何问题. 修改方法:__String::createWithFormat("%s", s_szFuWenEffect2[GetType()])

Error format not a string literal and no format arguments解决方案

原地址: http://blog.csdn.net/joeblackzqq/article/details/25985299 cData.cpp:355:30:error:format not a string literal and no fomat arguments [-Werror=format-security]cData.cpp:387:42:error:format not a string literal and no fomat arguments [-Werror=forma

std::string stringf(const char* format, ...)

std::string stringf(const char* format, ...){ va_list arg_list; va_start(arg_list, format); // SUSv2 version doesn't work for buf NULL/size 0, so try printing // into a small buffer that avoids the double-rendering and alloca path too... char short_b