I was just looking at the bitarray code and i thought that instead of a lot
of bitshifting and messing to retrieve individual bytes from int's it would
be faster (and easier?) to use unsafe code and mess with individual bytes
that way. This patch makes it about 20% faster to create a bit array from an
int[].

I'm not too sure if it's worth committing though.

Alan.
Index: C:/programming/mcs/class/corlib/System.Collections/BitArray.cs
===================================================================
--- C:/programming/mcs/class/corlib/System.Collections/BitArray.cs	(revision 74942)
+++ C:/programming/mcs/class/corlib/System.Collections/BitArray.cs	(working copy)
@@ -78,8 +78,18 @@
 			m_length = bytes.Length * 8;
 			m_array = new int [(m_length + 31) / 32];
 
-			for (int i = 0; i < bytes.Length; i++)
-				setByte (i, bytes [i]);
+			unsafe
+			{
+				fixed (int* ptr = &m_array[0])
+				{
+					byte* b = (byte*)(ptr);
+					for (int i = 0; i < bytes.Length; i++)
+						*(b++) = bytes[i];
+
+					if (bytes.Length != 0)
+						_version++;
+				}
+			}
 		}
 		
 		public BitArray (int [] values)
@@ -118,29 +128,6 @@
 #endregion
 #region Utility Methods
 		
-		byte getByte (int byteIndex)
-		{
-			int index = byteIndex / 4;
-			int shift = (byteIndex % 4) * 8;
-			
-			int theByte = m_array [index] & (0xff << shift);
-			
-			return (byte)((theByte >> shift) & 0xff);
-		}
-		
-		void setByte (int byteIndex, byte value)
-		{
-			int index = byteIndex / 4;
-			int shift = (byteIndex % 4) * 8;
-			
-			// clear the byte
-			m_array [index] &= ~(0xff << shift);
-			// or in the new byte
-			m_array [index] |= value << shift;
-			
-			_version++;
-		}
-		
 		void checkOperand (BitArray operand)
 		{
 			if (operand == null)
@@ -242,8 +229,15 @@
 				
 				byte [] barray = (byte []) array;
 				// Copy the bytes into the array
-				for (int i = 0; i < numbytes; i++)
-					barray [index + i] = getByte (i);
+				unsafe
+				{
+					fixed (int* ptr = &m_array[0])
+					{
+						byte* b = (byte*)(ptr);
+						for (int i = 0; i < barray.Length; i++)
+							barray[i] = *(b++);
+					}
+				}
 				
 			} else if (array is int []) {
 				
_______________________________________________
Mono-devel-list mailing list
Mono-devel-list@lists.ximian.com
http://lists.ximian.com/mailman/listinfo/mono-devel-list

Reply via email to