字符串插值和 string.format 中的哪一个在性能上更好? [英] Which of one from string interpolation and string.format is better in performance?

查看:26
本文介绍了字符串插值和 string.format 中的哪一个在性能上更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码:

var url = "www.example.com";

字符串格式:

var targetUrl = string.Format("URL: {0}", url);

字符串插值:

var targetUrl=$"URL: {url}";

字符串插值和string.Format哪个性能更好?

Which of one from string interpolation and string.Format is better in performance?

还有哪些最适合使用它们的场景?

Also what are the best fit scenarios for use of them?

推荐答案

字符串插值和 string.format 哪个性能更好?

Which of one from string interpolation and string.format is better in performance?

它们都不是更好,因为它们在运行时相等.字符串插值由编译器重写为string.Format,因此两个语句在运行时完全相同.

Neither of them is better since they are equal on run-time. String interpolation is rewritten by the compiler to string.Format, so both statements are exactly the same on run-time.

还有哪些最适合使用它们的场景?

Also what are the best fit scenarios for use of them?

如果您想在字符串格式中使用范围内的变量,请使用字符串插值.字符串插值更安全,因为它对字符串的有效性进行编译时检查.如果从外部源(如资源文件或数据库)加载文本,请使用 string.Format.

Use string interpolation if you have variables in scope which you want to use in your string formatting. String interpolation is safer since it has compile time checks on the validness of your string. Use string.Format if you load the text from an external source, like a resource file or database.

这篇关于字符串插值和 string.format 中的哪一个在性能上更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆