【问题标题】:More efficient for each loops每个循环更有效
【发布时间】:2011-07-26 09:50:51
【问题描述】:

有没有更有效的方法来编写这段代码?

For Each row As DataRow In dt.Rows
    Dim ts1 As String = row(0).ToString
    For index As Integer = 1 To 9
        Dim colName As String
        colName = dt.Columns(index).ToString
        For Each row2 As DataRow In dtAppAvail.Rows
            Dim colName2 As String
            Dim ts2 As String
            colName2 = row2("Day").ToString.Substring(0, 3) & " " & CType(row2("Date"), Date).ToString("dd/MM")
            ts2 = row2("Timeslot").ToString
            If colName = colName2 AndAlso ts1 = ts2 Then
                row(index) = row2("AppointmentsBooked")
            End If
        Next
    Next                            
Next

【问题讨论】:

  • 有效吗?慢吗?您是否有理由寻求提高效率?
  • 过早的eje..优化是万恶之源。
  • 它很慢,因为有很多 for 循环 - 试图减少它以使其更紧凑?
  • 我会研究 LINQ 来解决这个问题而无需循环。
  • 如果您的 DataRow 由数据库填充,我建议您执行特定查询以获取所需信息。

标签: vb.net optimization loops .net-2.0 performance


【解决方案1】:
For Each row As DataRow In dt.Rows
            For index As Integer = 1 To 9
                For Each row2 As DataRow In dtAppAvail.Rows
                    Dim colName2 As String = row2("Day").ToString.Substring(0, 3) & " " & CType(row2("Date"), Date).ToString("dd/MM")
                    If dt.Columns(index).ToString = colName2 AndAlso row(0).ToString = row2("Timeslot").ToString Then
                        row(index) = row2("AppointmentsBooked")
                    End If
                Next
            Next
        Next

这是一个更精简的版本... 它使用更少的变量,我假设 = 更少的内存存储,但我怀疑你会注意到很大的不同......

【讨论】:

    【解决方案2】:

    如果您的数据表很大,则使循环并行。 我会建议使用 .NET 4 附带的 parallel.foreach,但由于您指定了 .NET 2,因此您可以自己实现它。

    查看“并行编程模式”:

    http://www.microsoft.com/download/en/details.aspx?id=19222
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2015-01-24
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      相关资源
      最近更新 更多