Array.indexof Performance Caveat

xiaoxiao2021-03-06  64

Array.indexof is "Generic" Methods to search for An Item in an ONE Dimensional Array. However Since They Are Generic, There Are Some Performance Caveats.

Array.indexOf Handles Arrays in Three Different Ways:

(1) If the array is a SZArray (one dimensional array with zero-based indexing) and element type is one of following types: Byte, SByte, Boolean, Int16, UInt16, Char, Int32, UInt32, Int64, UInt64, Single, Double, The Search Will BE DONE IN UNMANAGED CODE. This Will Be Pretty Fast. Note We do need.

(2) IF The array is a szaRay of Reference Type, We can Object.Equals on each value in the array unsage. This is not bad each.

(3) When the array is a szarray of other value type or the limited zero, The code is like:

For (int i = startIndex; i

Object obj = array.getvalue (i);

Value.equals (obj)) RETURN I;

}

GetValue is quite costly and the worst part is it could cause boxing for each items in the array we searched for. I wrote a simple test to search for an item in an Array of a simple custom value type. Using for loop to search for an Itemsin The Array Is About 40x Faster Than Calling Array.indexof.

Generics comes to rescue here. The performance problem does not exist for SZArray on Whidbey. C # compiler favors IndexOf . So if you recompile your code on Whidbey, you could get rid of the performance problem for free. (Note the generic Version is actually sloo the Non-generic version under some case on whidbey beta1 build. we will fix what before whidbey ships.)

There is the two of the are two other thing

(1) Array.indexof Doesn't Support Conversion Between Primitive Types. Following Code Will Print Out -1.long [] array = new long [10];

For (int i = 0; i <10; i ) {array [i] = i;}

Console.WriteLine (Array.indexof (Array, 9));

(2) The item to be selfched is passed in as object. Sore is a boxing Operation for ISDEXOF IS CALED IN FOLLOWING CODE:

Int [] array = new int [10];

...

Array.indexof (Array, 9);

.

转载请注明原文地址:https://www.9cbs.com/read-89780.html

New Post(0)