Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.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# - Fatal编程技术网

C# 附加一个字符串还是一个字符更有效?

C# 附加一个字符串还是一个字符更有效?,c#,C#,就绩效而言,在以下方面是否存在差异: stringX+y与stringX+y 如果有区别,为什么有区别 我的问题主要与C有关。两者之间绝对没有区别。例如,如果您具有以下两个功能: static string Method1() { var stringX = "abc"; var res = stringX + 'y'; return res; } static string Method2() { var stringX = "abc"; var re

就绩效而言,在以下方面是否存在差异: stringX+y与stringX+y

如果有区别,为什么有区别


我的问题主要与C有关。

两者之间绝对没有区别。例如,如果您具有以下两个功能:

static string Method1()
{
    var stringX = "abc";
    var res = stringX + 'y';
    return res;
}

static string Method2()
{
    var stringX = "abc";
    var res = stringX + "y";
    return res;
}
以下是C编译器在发布模式下生成的相应IL:

.method private hidebysig static string Method1 () cil managed 
{
    IL_0000: ldstr "abc"
    IL_0005: ldstr "y"
    IL_000a: call string [mscorlib]System.String::Concat(string,  string)
    IL_000f: ret
}

.method private hidebysig static string Method2 () cil managed 
{
    IL_0000: ldstr "abc"
    IL_0005: ldstr "y"
    IL_000a: call string [mscorlib]System.String::Concat(string,  string)
    IL_000f: ret
}

编译器具有足够的智能,能够为极不寻常的stringX+'y'构造发出适当的IL。

为什么不在发出请求之前对其进行测试?StringBuildery您的时间最好花在思考其他问题上。像这样的事情永远不会成为你最大的瓶颈,如果你真的想优化它,就要针对可读性而不是性能进行优化。@LP.Gonçalves:如果他在问之前测试过,他就不需要问了it@JamesHughes:我建议使用。在发行版中编译,然后启动基准测试应用程序,而不是在VisualStudio中,而是在exe中。这是试验的总结:方法平均标准试验数据偏差版本1:17.0179 ns 0.1315 ns版本2:17.1224 ns 0.3225 ns