【发布时间】:2014-02-03 14:16:09
【问题描述】:
C# 编译器足够智能,可以将使用 + 运算符的字符串连接优化为 String.Concat 调用。
以下代码:
var a = "one";
var b = "two";
var c = "three";
var d = "four";
var x = a + b + c + d;
被编译成这个IL:
IL_0000: ldstr "one"
IL_0005: stloc.0 // a
IL_0006: ldstr "two"
IL_000B: stloc.1 // b
IL_000C: ldstr "three"
IL_0011: stloc.2 // c
IL_0012: ldstr "four"
IL_0017: stloc.3 // d
IL_0018: ldloc.0 // a
IL_0019: ldloc.1 // b
IL_001A: ldloc.2 // c
IL_001B: ldloc.3 // d
IL_001C: call System.String.Concat
编译器找出正确的 String.Concat 重载,它接受 4 个参数并使用它。
F# 编译器不这样做。相反,每个+ 都被编译成一个单独的String.Concat 调用:
IL_0005: ldstr "one"
IL_000A: ldstr "two"
IL_000F: call System.String.Concat
IL_0014: ldstr "three"
IL_0019: call System.String.Concat
IL_001E: ldstr "four"
IL_0023: call System.String.Concat
显然这是因为 F# 编译器中没有实现这种特殊优化。
问题是为什么:技术上很难做到还是有其他原因?
字符串连接是一种相当常见的操作,虽然我意识到编译代码的性能并不是最重要的,但我想这种优化在很多情况下都会很有用。
【问题讨论】:
标签: f#