I want to know the fastest way to check if an array is empty in VB.NET. The array is already initialized so I can't use any of the checks that look at that. This is the current code below:
If Not (cubes(threadnumber)(i).objects.GetLength(0) = 0) Then
cubes(threadnumber)(i).objects = New Double() {}
ReDim cubes(threadnumber)(i).objects(-1)
End If
I've done some testing and I know that using .GetUpperBound
is a little faster, but I'm not sure if this will work because I think .GetUpperBound
returns a 0 if the array length is 1.
Any/all methods to speed this up (even fractionally) will be tremendously helpful. This program takes ages to compleate and the first line of the above code is a big portion of the time, it's called 136 million times.
Also if anyone knows how to speed up For...Next loops that'd be great too!
GetLength is the fastest way I know of to see if an array has elements in it.
The isEmpty() method of ArrayList in java is used to check if a list is empty or not. It returns true if the list contains no elements otherwise it returns false if the list contains any element.
empty() function is used to check if the array container is empty or not.
If the length of the object is 0, then the array is considered to be empty and the function will return TRUE. Else the array is not empty and the function will return False.
Length
is about 2x faster than GetLength
on my system (calling Length
136M times takes 0.650 seconds, while calling GetLength (0)
takes 1.480 seconds).
I also do not understand why you ReDim your array, you've already created a new one.
I believe this will be the fastest code if cubes is a multi-dimensional array:
If cubes(threadnumber)(i).objects.Length > 0 Then
cubes(threadnumber)(i).objects = New Double() {}
End If
If cubes is not a multi-dimensional array (like List for instance), you should take the cubes(threadnumber)
code out of the loop.
Update
Length
is 6x faster than GetLength
when running in Release mode without the debugger, in which case Length
takes 0.181s and GetLength
1.175s on my system. This is likely because the JIT will inline the call to Length
, but not the call to GetLength
.
This is the test code I used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With