Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest method to check if an array is empty

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!

like image 662
FraserOfSmeg Avatar asked Nov 22 '12 05:11

FraserOfSmeg


People also ask

How check array is empty in VB net?

GetLength is the fastest way I know of to see if an array has elements in it.

How do you check the array is empty or not in Java?

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.

How do you check if an array is empty or not in C++?

empty() function is used to check if the array container is empty or not.

Is array length 0 Falsy?

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.


2 Answers

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.

like image 65
Rolf Bjarne Kvinge Avatar answered Oct 20 '22 19:10

Rolf Bjarne Kvinge


if myarray is nothing then...

or

if myarray isnot nothing then...
like image 21
sj1900 Avatar answered Oct 20 '22 20:10

sj1900