我正在尝试创建一个用户可修改的字符串,该字符串已经设置了数据以替换某些文本补丁
例如
dim name1 as string = "John"
dim state as string = "Virginia"
dim idnumb as integer = 122
dim textlist1 as string
textlist1 = "Hello {NAME}, I see you are from {STATE}, and your id number is {ID}."
理想情况下,我想用set string
替换这些标签我熟悉
Replace(textlist1, "{NAME}", name1)
我的问题是:这是正确的方法吗?还是有一种方法更像我们在MySql中做参数的方式
答案 0 :(得分:1)
理想情况下,您可以使用StringBuilder来避免为每个替换重新分配新字符串。
dim name1 as string = "John"
dim state as string = "Virginia"
dim idnumb as integer = 122
dim textlist1 as StringBuilder = new StringBuilder _
("Hello {NAME}, I see you are from {STATE}, and your id number is {ID}.")
textlist1.Replace("{NAME}", name1)
假设StringBuilder方法不是性能相关比较的最佳方法 这只是通过LinqPad执行的一个小基准
Sub Main
dim name1 as string = "John"
dim state as string = "Virginia"
dim idnumb as integer = 122
dim textlist1 as StringBuilder
Dim sw = new Stopwatch()
sw.Start()
for i = 0 to 100000
textlist1 = new StringBuilder("Hello {NAME}, I see you are from {STATE}, and your id number is {ID}.")
textlist1.Replace("{NAME}", name1)
textlist1.Replace("{STATE}", state)
textlist1.Replace("{ID}", idnumb.ToString())
Next
sw.Stop()
sw.Elapsed.Dump("StringBuilder.Replace")
sw = new Stopwatch()
sw.Start()
for i = 0 to 100000
Dim test = "Hello {NAME}, I see you are from {STATE}, and your id number is {ID}."
Dim test2 = test.Replace("{NAME}", name1)
Dim test3 = test2.Replace("{STATE}", state)
Dim test4 = test3.Replace("{ID}", idnumb.ToString())
Next
sw.Stop()
sw.Elapsed.Dump("String.Replace")
End Sub
StringBuilder.Replace
00:00:00.2795878
String.Replace
00:00:00.1642420
因此,分配字符串生成器的成本似乎超过了使用固定的实习字符串的成本。当然,由不可变字符串行为引起的内存碎片不容易测量。