-2

哪个更快?someCondition 为真的概率与它为假的概率相同。

插入:

arrayList = Array("apple", "pear","grape")
if someCondition then
    ' insert "banana" element
end if

删除:

arrayList = Array("apple","banana","pear","grape")
if not someCondition then
    ' remove "banana" element
end if

看起来它完全取决于插入和删除的实现。那么,一般来说,哪个更快?我倾向于插入,因为我读过可以使用 CopyMemory 插入而无需循环。删除也是一样的吗?有人有例子吗?

编辑:这是 VB6,而不是 VB.NET。出于显示原因,我必须使用插入而不是附加。

4

5 回答 5

1

两者的性能大致相同,因为两者都需要创建一个新数组。数组是固定大小的连续结构。

为了在插入时保持这一点,必须使用附加元素创建一个新数组。所有现有值都被复制到数组中的新位置,然后添加插入的元素。

为了在删除时保持这一点,必须创建一个少一个元素的新数组。然后必须将除删除之外的所有现有条目复制到新数组中。

这两个操作在几乎相同的大小上具有基本相同的操作。性能不会有显着差异。

于 2008-10-13T16:27:25.040 回答
1

对于删除,删除项目之后的每个项目都必须向下移动。

对于插入,必须为新项目找到空间。如果可以吞并的数组后面有空的空间,那么这不会花时间,唯一花费的时间是在新项目之后的每个项目更多,以便在中间腾出空间。

如果本地没有可用空间,则必须分配一个全新的数组并复制每个项目。

因此,当考虑添加或删除相同的数组位置时,插入可能与删除一样快,但可能要长得多。插入不会更快。

于 2008-10-13T16:28:24.260 回答
0

我找到了一个例子,表明一个人也可以在不循环的情况下删除。它看起来比要插入的代码更简单。

Public Sub RemoveArrayElement_Str(AryVar() As String, ByVal _
    RemoveWhich As Long)
    '// The size of the array elements
    '// In the case of string arrays, they are
    '// simply 32 bit pointers to BSTR's.
    Dim byteLen As Byte

    '// String pointers are 4 bytes
    byteLen = 4

    '// The copymemory operation is not necessary unless
    '// we are working with an array element that is not
    '// at the end of the array
    If RemoveWhich < UBound(AryVar) Then
        '// Copy the block of string pointers starting at
        ' the position after the
        '// removed item back one spot.
        CopyMemory ByVal VarPtr(AryVar(RemoveWhich)), ByVal _
            VarPtr(AryVar(RemoveWhich + 1)), (byteLen) * _
            (UBound(AryVar) - RemoveWhich)
    End If

    '// If we are removing the last array element
    '// just deinitialize the array
    '// otherwise chop the array down by one.
    If UBound(AryVar) = LBound(AryVar) Then
        Erase AryVar
    Else
        ReDim Preserve AryVar(UBound(AryVar) - 1)
    End If
End Sub

http://www.vb-helper.com/howto_delete_from_array.html

于 2008-10-13T16:15:03.117 回答
0

我不得不猜测插入,因为它总是可以追加,而删除你必须担心漏洞。

但是什么版本的vb?如果您在 .Net 中执行删除或插入操作,则根本不应该为此使用数组。

于 2008-10-13T16:15:09.357 回答
0

关于主题但不是一个完整的答案:

插入和删除不是适用于数组的应用程序。它超越了“优化”并进入了糟糕的编程。

如果这隐藏在调用结构的底部并且有人最终重复调用它,您可能会受到严重的性能影响。在一种情况下,我将数组插入排序更改为仅使用链表,并将运行时间从 10+小时(锁定机器)更改为秒/分钟)。

它正在用 ip 地址填充一个列表框。正如在 c 类地址空间上设计和测试的那样,它运行良好,但我们要求在 b 类地址空间上工作而不会失败(可能需要一段时间,但不是几个小时)。我们的任务是尽可能减少重构以使其不会失败。

不要假设你知道你的 hack 将如何被使用。

于 2008-10-13T17:41:07.590 回答