C#中关于字符串的两种拼接比较:string和stringBuilder方式

C#中常用直接相加的方式进行字符串拼接,但是还有一种StringBuilder的拼接方式,现在对比他们之间的性能影响。
C#代码如下

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace NiuKe_TEST
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            UserContrast.UserFirstWay("HAHA", 60000);
            sw.Stop();
            Console.WriteLine("使用字符串拼接60000次耗时:" + sw.ElapsedMilliseconds);

            //sw.Start();
            //UserContrast.UserSecWay("HAHA", 60000);
            //sw.Stop();
            //Console.WriteLine("使用StringBuilder拼接60000次耗时:" + sw.ElapsedMilliseconds);
        }        
        
    }
    public static class UserContrast
    {
        public static string UserFirstWay(string strValue, int num)
        {
            string result = "";
            for(int i=0;i<num;i++)
            {
                result += strValue + i;
            }
            return result;
        }
        public static string UserSecWay(string strValue, int num)
        {
            StringBuilder sb = new StringBuilder();            
            for (int i = 0; i < num; i++)
            {
                sb.Append(strValue+i);
            }
            return sb.ToString();
        }
    }
}

通过上述代码我的机子跑出来分别是使用传统的相加和StringBuilder进行字符串的拼接耗时分别是10615ms和13ms,由此可看出来使用StringBuilder的进行字符串的拼接速度快了不只是一点点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值