此功能大约需要1.2秒才能执行。我无法理解为什么?是因为内部连接?如果是,那我怎样才能提高执行速度?我正在使用Microsoft Enterprise Library。
Public Shared Function GetDataByInterests(ByVal accountId As Integer) As Object
Dim details As New List(Of GetIdBasedOnInterest)()
Dim getIDs As New GetIdBasedOnInterest
Dim interests As String = ""
Dim db As SqlDatabase = Connection.Connection
Using cmdGeneric As DbCommand = db.GetSqlStringCommand("SELECT Interests.InterestName FROM UserInterests INNER JOIN Interests ON UserInterests.InterestID = Interests.InterestID WHERE UserInterests.AccountID=@AccountID")
db.AddInParameter(cmdGeneric, "AccountID", SqlDbType.Int, accountId)
Dim dsInterests As DataSet = db.ExecuteDataSet(cmdGeneric)
For i = 0 To dsInterests.Tables(0).Rows.Count - 1
If i = dsInterests.Tables(0).Rows.Count - 1 Then
interests = interests & dsInterests.Tables(0).Rows(i).Item(0).ToString
Else
interests = interests & dsInterests.Tables(0).Rows(i).Item(0).ToString & ","
End If
Next
End Using
getIDs.InterestName = interests
details.Add(getIDs)
Return details
End Function
答案 0 :(得分:1)
在不知道基础表及其索引的任何内容的情况下(这是一个你应该立即进行的检查),你的循环中存在明显的问题。
你可以使用字符串,这可能会对程序使用的内存造成很大的压力
字符串连接导致在内存上分配新字符串,因此,如果您的表包含许多行,则效果可能会很明显。
您可以尝试使用StringBuilder
Dim interests As new StringBuilder(1024) ' suppose an internal buffer of 1K'
...
If i = dsInterests.Tables(0).Rows.Count - 1 Then
interests.Append(dsInterests.Tables(0).Rows(i).Item(0).ToString)
Else
interests.Append(dsInterests.Tables(0).Rows(i).Item(0).ToString & ",")
End If
....
getIDs.InterestName = interests.ToString
当然,如果您的表格UserInterests
和Interests
)未在字段InterestID
和AccountID
编辑:另一个微优化是删除内部IF测试并在循环结束后截断结果输出
For ....
interests.Append(dsInterests.Tables(0).Rows(i).Item(0).ToString & ",")
Next
if(interest.Length > 0) interest.Length -= 1;
编辑至于您的请求,这是创建唯一索引的示例。语法可能更复杂,并且根据Sql Server版本的不同而有所不同,但基本上你是在Sql Management Studio中执行此操作
CREATE UNIQUE INDEX <indexname> ON <tablename>
(
<columntobeindexed>
)
检查MSDN上的CREATE INDEX语句示例
答案 1 :(得分:1)
1)在SQL Server Management Studio中查询您的查询。将它与VB代码隔离在一起更加容易。您还可以运行显示查询计划,甚至可以建议新索引。
2)检查是否已定义相关的主键和索引。
3)将常用表达式从for循环中拉出来,以避免反复重复计算同样的事情:
4)像Steve所说,使用StringBuilder
结合这些要点:
Dim theTable as ...
Dim rowCount as Integer
Dim interests As new StringBuilder(1024)
Set theTable = dsInterests.Tables(0)
rowCount = theTable.Rows.Count
For i = 0 To rowCount - 1
interests.Append(theTable.Rows(i).Item(0).ToString)
If i <> rowCount - 1 Then
interests.Append(",")
End If
Next