字符串直接赋值与替换性能对比

在这里插入图片描述
于是我在想,为什么不直接进行赋值来进行变换,而通过替换局部字符串来变换呢?两者之间有什么区别?到底哪一种的性能会好点?于是带着种种疑问,设计了如下实验:

复制代码
using System;
using System.Diagnostics;

namespace test
{
class Program
{
static void Main(string[] args)
{
var str1 = “转到编辑界面”;
var num = 0;
while (num < 5)
{
test1(str1);
test2(str1);
num += 1;
         System.Console.WriteLine("=====================");
}
}

    private static void test1(string str1)
    {
        var num = 0; var str = str1;
        var sw = new Stopwatch();
        sw.Start();
        while (num < 100000)
        {
            if (str == str1)
                str = str.Replace("编辑", "预览");
            else
                str = str.Replace("预览", "编辑");
            num += 1;
        }
        sw.Stop();
        System.Console.WriteLine(sw.ElapsedMilliseconds);
    }

    private static void test2(string str1)
    {
        var num = 0; var str = "";
        var sw = new Stopwatch();
        sw.Start();
        while (num < 100000)
        {
            str = str == str1 ? "转到预览界面" : "转到编辑界面";
            num += 1;
        }
        sw.Stop();
        System.Console.WriteLine(sw.ElapsedMilliseconds);
    }
}

}
亚马逊测评www.yisuping.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值