计数较大时,循环会持续很长时间
这个循环需要永远运行,因为循环中的项目数量接近或超过 1,000,接近 10 分钟。这需要快速运行,金额高达 30-40,000。
'Add all Loan Record Lines
Dim loans As List(Of String) = lar.CreateLoanLines()
Dim last As Integer = loans.Count - 1
For i = 0 To last
If i = last Then
s.Append(loans(i))
Else
s.AppendLine(loans(i))
End If
Next
s 是一个 StringBuilder。 即使有数千条记录,第一行也
Dim loans As List(Of String) = lar.CreateLoanLines()
只需几秒钟即可运行。这是实际的循环,需要一段时间。
这该如何优化???
This loop takes forever to run as the amount of items in the loop approach anything close to and over 1,000, close to like 10 minutes. This needs to run fast for amounts all the way up to like 30-40 thousand.
'Add all Loan Record Lines
Dim loans As List(Of String) = lar.CreateLoanLines()
Dim last As Integer = loans.Count - 1
For i = 0 To last
If i = last Then
s.Append(loans(i))
Else
s.AppendLine(loans(i))
End If
Next
s is a StringBuilder. The first line there
Dim loans As List(Of String) = lar.CreateLoanLines()
Runs in only a few seconds even with thousands of records. It's the actual loop that's taking a while.
How can this be optimized???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
将 StringBuilder 的初始容量设置为一个较大的值。 (理想情况下,足够大以包含整个最终字符串。)就像这样:
如果您不指定容量,构建器可能最终会进行大量的内部重新分配,这会降低性能。
Set the initial capacity of your StringBuilder to a large value. (Ideally, large enough to contain the entire final string.) Like so:
If you don't specify a capacity, the builder will likely end up doing a large amount of internal reallocations, and this will kill performance.
您可以将特殊情况从循环中取出,这样您就不需要在循环内检查它。不过,我预计这对性能几乎没有影响。
You could take the special case out of the loop, so you wouldn't need to be checking it inside the loop. I would expect this to have almost no impact on performance, however.
不过,在内部,代码非常相似,如果您使用 .NET 4,我会考虑通过一次调用来替换您的方法 String.Join:
Though, internally, the code is very similar, if you're using .NET 4, I'd consider replacing your method with a single call to String.Join:
我看不出您指出的代码可能会很慢,除非:
尝试逐行单步执行代码并检查字符串是否包含您期望的数据,然后检查任务管理器以查看您的应用程序正在使用多少内存以及您有多少可用内存。
I can't see how the code you have pointed out could be slow unless:
Try stepping through the code line by line and check that the strings contain the data that you expect, and check Task Manager to see how much memory your application is using and how much free memory you have.
我的猜测是,每次使用追加时,它都会创建一个新字符串。您似乎知道需要多少内存,如果您首先分配所有内存,然后将其复制到内存中,它应该运行得更快。虽然我可能对 vb.net 的工作原理感到困惑。
My guess would be that every time you're using append it's creating a new string. You seem to know how much memory you'll need, if you allocate all of the memory first and then just copy it into memory it should run much faster. Although I may be confused as to how vb.net works.
你可以考虑用另一种方式来做这件事。
You could look at doing this another way.