使用字符串插值插入常量是否有运行时开销?

托比·史密斯

我有一个包含3个方法的类,每个方法都启动一个新方法,System.Diagnostics.Process其中传递了一些唯一的参数以及所有这3个参数所共享的一些标准参数。

为了减少重复,我目前将所有一致的参数存储为类级常量,然后在方法运行时对其进行插值。

private const string File = "file.exe";
private const string StandardAgs = "--whatever";

public void DoA()
{
    string command = $"{File} unique args for A {StandardAgs}";
    Process.Start(command);
}

public void DoB()
{
    string command = $"{File} unique args for B {StandardAgs}";
    Process.Start(command);
}

public void DoC()
{
    string command = $"{File} unique args for C {StandardAgs}";
    Process.Start(command);
}

此插值有运行时处理开销吗?还是因为所有类级变量都是常量,编译器会认识到可以在编译时进行插值吗?

失败了,我是否需要使我所有的字符串都保持常数以实现零运行时插值,像这样?

private const string File = "file.exe";
private const string StandardAgs = "--whatever";

private const string Acommand = $"{File} unique args for A {StandardAgs}";
private const string Bcommand = $"{File} unique args for B {StandardAgs}";
private const string Ccommand = $"{File} unique args for C {StandardAgs}";

public void DoA()
{
    Process.Start(Acommand);
}

public void DoB()
{
    Process.Start(Bcommand);
}

public void DoC()
{
    Process.Start(Ccommand);
}

我认识到,只有第二个示例将字符串静态地存储在内存中,而不是基于每个实例,但是我不关心内存占用量,只关心在运行时发生多少字符串插值。

我写了一个简短的程序,然后通过ILSpy运行它。

C#:

const string Foo = "Hello";

static void Main()
{
    var bar = $"{Foo}Bar!";
    Console.WriteLine(bar);
}

IL_0001: ldstr "{0}Bar!"
IL_0006: ldstr "Hello"
IL_000b: call string [mscorlib]System.String::Format(string, object)
IL_0010: stloc.0
IL_0011: ldloc.0
IL_0012: call void [mscorlib]System.Console::WriteLine(string)

看起来它变成了string.Format调用并在运行时进行了计算。

是的,这对性能有非常小的影响。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在运行时使用字符串/变量访问常量

Groovy字符串插值,其值仅在运行时已知

使用字符串插值时是否可以混合字符串资源?

为什么在struct中使用字符串时出现运行时错误

每个内部使用字符串时发生运行时错误

使用字符串插值进行函数调用

使用字符串插值进行模式匹配

如何使用字符串插值

如何使用字符串插值打印$

使用零运行时开销(Swift)从字符串文字初始化CChar或UInt8

朱莉娅似乎没有使用字符串来执行插值

在运行时在字符串中设置值

有沒有辦法忽略轉義字符但仍然使用字符串插值?C#

如何在字符串文字中使用字符串插值?

如何在Groovy多行字符串中使用字符串插值?

使用字符串插值将字符串格式化为列

在运行时使用字符串创建T且不会丢失智能感知

使用在运行时之前未知的转义值(变量)构造字符串

使用字符串插值的字符串连接

在运行时从base64编码的字符串中应用字体

在颤振中使用字符串值而不是常量字符串

如何在运行时在Objective-C中查找字符串常量?

使用字符串插值法,如何填充给定字符?

如何在Less中使用字符串对地图值进行插值

使用字符串插值访问 dartlang 中嵌套映射中的值

Excel VBA - 使用 .ModifyAppliesTo 和运行时错误 1004(尝试插入太长的字符串时出现问题?)

您可以在Swift字符串插值中使用字符串/字符文字吗?

Scala-在Trait内使用字符串插值包含未实现的变量

在Angular2 App中使用字符串插值从数组中提取值