hCORe писал(а):Кстати, именно эффективная работа с ключами и поддержка For Each... - преимущества коллекций.
hCORe писал(а):Перед массивами.
...
Я прав?
Dim v
For Each v In Array("А", "ты", "знал,", "что", "такое", "возможно?")
Debug.Print v; " ";
Next
hCORe писал(а):Да. Но это массив типа Variant. Что уже изначально не есть хорошо.
Тем более, коллекции чуть-чуть более наглядны, чем массивы... И более оптимизированы, чем массивы типа Variant.
Dim v, foo(5) As Long
foo(1) = 5: foo(2) = 3: foo(3) = 4: foo(4) = 2: foo(5) = 1
For Each v In foo
Debug.Print v;
Next
Option Explicit
Private Declare Function GetTickCount Lib "kernel32" () As Long
Dim lCurTime As Long
Private Sub cmdArr_Click()
lCurTime = GetTickCount()
Dim i As Variant
Dim myArr(512) As Variant
For i = LBound(myArr) To UBound(myArr)
myArr(i) = Int(100000 * Rnd)
Next i
For Each i In myArr
Debug.Print i
Next i
txtArr.Text = "result: " & GetTickCount - lCurTime
End Sub
Private Sub cmdColl_Click()
lCurTime = GetTickCount()
Dim i As Variant
Dim myColl As New Collection
For i = 0 To 512
myColl.Add Int(100000 * Rnd), "Var" & i
Next i
For Each i In myColl
Debug.Print i
Next i
txtColl.Text = "result: " & GetTickCount - lCurTime
End Sub
hCORe писал(а):
Если ему нужна скорость операций - пусть выбирает двумерный массив.
hCORe писал(а):
Но коллекция - это встроенный тип данных. Притом - не самый плохой.
For i = 0 To 512
If myColl.Item("Var" & i) > 50000 And myColl.Item("Var" & i) < 80000 Then
myColl.Remove ("Var" & i)
End If
Next i
hCORe писал(а):Перед массивами. Я не спорю, что можно создать класс для хранения данных на основе массивов, реализующий IENUMVariant, и получить тот же самый for each.
hCORe писал(а):Все равно у коллекции есть преимущества перед массивами.
hCORe писал(а):В зависимости от конкретной задачи, решение может быть разным: простой двумерный массив, коллекция, расширенная структура данных на основе массивов. И что будет быстрее - во многом зависит от спектра выполняемых задач. Естественно, можно индексировать массивы. Только зачем? Если коллекция обеспечивает приемлемое быстродействие при выборке по ключу?..
newonline писал(а):Большую часть цикла обработки данных Collection будет работать с ключами
Visual Basic Concepts. Optimizing Code.
< ... >
Take Advantage of Collections
The ability to define and use collections of objects is a powerful feature of Visual Basic. While collections can be very useful, for the best performance you need to use them correctly:
Use For Each...Next rather than For...Next.
Avoid using Before and After arguments when adding objects to a collection.
Use keyed collections rather than arrays for groups of objects of the same type.
Collections allow you to iterate through them using an integer For...Next loop. However, the For Each...Next construct is more readable and in many cases faster. The For Each...Next iteration is implemented by the creator of the collection, so the actual speed will vary from one collection object to the next. However, For Each...Next will rarely be slower than For...Next because the simplest implementation is a linear For...Next style iteration. In some cases the implementor may use a more sophisticated implementation than linear iteration, so For Each...Next can be much faster.
It is quicker to add objects to a collection if you don't use the Before and After arguments. Those arguments require Visual Basic to find another object in the collection before it can add the new object.
When you have a group of objects of the same type, you can usually choose to manage them in a collection or an array (if they are of differing types, a collection is your only choice). From a speed standpoint, which approach you should choose depends on how you plan to access the objects. If you can associate a unique key with each object, then a collection is the fastest choice. Using a key to retrieve an object from a collection is faster than traversing an array sequentially. However, if you do not have keys and therefore will always have to traverse the objects, an array is the better choice. Arrays are faster to traverse sequentially than collections.
For small numbers of objects, arrays use less memory and can often be searched more quickly. The actual number where collections become more efficient than arrays is around 100 objects; however, this can vary depending on processor speed and available memory.
For More Information See "Using Collections as an Alternative to Arrays" in "More About Programming."
hCORe писал(а):From a speed standpoint, which approach you should choose depends on how you plan to access the objects. If you can associate a unique key with each object, then a collection is the fastest choice. Using a key to retrieve an object from a collection is faster than traversing an array sequentially. However, if you do not have keys and therefore will always have to traverse the objects, an array is the better choice. Arrays are faster to traverse sequentially than collections.
Сейчас этот форум просматривают: Google-бот и гости: 103