1
Public Function gridloop(MSFG1 As Object) As Long
     For  i= 0 To MSFG1.rows - 1 
            A = MSFG1.TextMatrix(i,1)
        Next
End Function

上面的代码比下面的慢 2 倍

Public Function gridloop(MSFG1 As MSHFlexGrid) As Long
Public Function gridloop(MSFG1 As MSFlexGrid) As Long

有什么办法可以加速吗?

4

3 回答 3

3

问题中没有太多细节,我想你有两个(或更多?)不同的控件,你试图从本质上重载你的gridloop函数,以便它可以与多种类型的控件一起使用?

以下可能会提供性能改进。我没有对此进行测试,甚至没有确认它没有编译错误。想法是确定控件类型,然后将其分配给匹配类型的变量,然后对方法和属性的引用可能会被提前绑定(因此更快)。

Public Function gridloop(MSFG1 as Object) as Long
  Dim myMSHFlexGrid As MSHFlexGrid
  Dim myMSFlexGrid As MSFlexGrid
  Dim i As Integer
  Dim A As Long

  If TypeOf MSFG1 Is MSHFlexGrid Then
    Set myMSHFlexGrid = MSFG1 
    For  i = 0 To myMSHFlexGrid.rows - 1 
      A = myMSHFlexGrid.TextMatrix(i,1)
    Next
  ElseIf TypeOf MSFG1 Is MSFlexGrid Then
    Set myMSFlexGrid = MSFG1 
    For  i = 0 To myMSFlexGrid.rows - 1 
      A = myMSFlexGrid.TextMatrix(i,1)
    Next
  End If

End Function

另一种方法是定义两个gridloop函数,每个类型一个。手动重载的一种形式。

Public Function gridloop_MSHFlexGrid(MSFG1 As MSHFlexGrid) As Long
Public Function gridloop_MSFlexGrid(MSFG1 As MSFlexGrid) As Long

这样做的好处是,尝试gridloop使用“不正确”控件调用其中一个函数将导致编译错误 - 及早发现问题,否则可能需要花费大量时间执行运行时调试。

于 2018-07-24T13:47:46.913 回答
1

基于MarkL 的答案,您可以使用实际的 VB 接口重载来获得您想要的。

这个想法是创建一个接口,在网格上公开您需要的任何属性或功能,然后创建两个类,每个类都实现该接口并在内部操作实际的网格。

这种包装替代了两种网格类型本质上不共享公共接口的事实。(我使用 OLEView 查看了 IDL)。

然后,您可以使用该接口作为您当前Object用于代表实际网格类的每个位置的类型。如果接口是全面的并且它的方法/属性被适当地命名,那么您不需要进行任何其他代码更改。

示例(伪)代码...

界面:

'In file for interface IGridWrapper

Function Rows
End Function

Function TextMatrix(i as Integer, j as Integer)
End Function

'Any others...

包装类 1:

' In file for class "MSFlexGridWrapper"

Implements IGridWrapper

Private m_grid as MSFlexGrid

Sub Init(MSFlexGrid grid)
  Set m_grid = grid
End Sub

Function IGridWrapper_Rows
   IGridWrapper_RowCount = m_grid.Count
End Function

Function IGridWrapper_Textmatrix(i as Integer, j as Integer)
   'etc.
End Function

'Any others...

包装类 2:

' In file for class "MSHFlexGridWrapper"

Implements IGridWrapper

Private m_grid as MSHFlexGrid

Sub Init(MSHFlexGrid grid)
  Set m_grid = grid
End Sub

Function IGridWrapper_Rows
   IGridWrapper_RowCount = m_grid.Count
End Function

Function IGridWrapper_Textmatrix(i as Integer, j as Integer)
   'etc.
End Function

'Any others...

使用包装器的代码:

Public Function gridloop(MSFG1 As IGridWrapper) As Long

(注意 - 这些都没有通过编译器进行精确的语法检查)

于 2018-07-30T16:23:48.230 回答
1

后期绑定(在运行时绑定)比早期绑定(在编译时绑定)慢的基本原因是您必须使用iDispatch接口GetIDsOfNamesInvoke方法来访问对象接口中的属性,而不是直接从 vtable 访问它们。有关更多信息,请查看

DaveInCaz 和 MarkL 的建议可能会加快速度的原因是它们是允许您的gridloop函数接受可以提前绑定的类型而不是Object类型的方法。DaveInCaz 的解决方案也是多态性实际应用的一个很好的例子。

于 2018-08-02T01:51:59.483 回答