What is the application of C # array initialization in data compression? We often use arrays. All elements of the array need to be zeroed at every point. Because C # does not provide a memset () method. So let's try the following test.
C # array initialization main parts of the program:
static void Main(string[] args)
{
int i,k;
double p = 0;
DateTime s, e;
byte[] test = new byte[65536];
byte[] test2 = new byte[65536];
for(int i = 0; i < 10; i++)
{
s = DateTime.Now;
for(j=0; j<50000; j++)
{
//***************//
}
e = DateTime.Now;
TimeSpan c = e - s;
Console.WriteLine(c.TotalMilliseconds.ToString());
p += c.TotalMilliseconds;
}
p /= 10;
Console.WriteLine("***" + p.ToString() + "***");
Console.Read();
}
Replace the annotation part in the following ways:
1.test = new byte[65536];
This method is obvious and easy to understand, each time a new array, the value of which is certainly 0.
2.memset (test,0,65536);
Imitate C + + Write a memset function:
public static void memset(byte[] buf, byte val, int size)
{
int i;
for(i=0; i < size; i++)
buf[i] = val;
}
3.for (k = 0; k < 65536; test[k++] = 0);
Writes the function memset directly to the annotation part. The idea is simple, saving the overhead of calling a function.
4.array.clear (test,0,65536);
Direct use. NET Self-band method.
5.test2. CopyTo (test, 0);
Copies content to the destination array with an empty array.
Then the test is done and the results are as follows:
Method the longest and shortest average
Method 1: The longest 1937.5 shortest 1812.5 average 1842.1875
Method 2: The longest 4593.75 shortest 4625 average 4584.375
Method 3: The longest 6046.875 shortest 5984.375 average 6001.5625
Method 4: The longest 562.5 shortest 640.5 average 581.25
Method 5: The longest 812.5 shortest 750 average 770.3125
Computer: p43.0e (Hyper-threading on)/ddr400 512M (dual channel) Software environment: Win xp-sp2/vs2003 Unit: MS
The result is clearly that the Array.clear () method is the ultimate winner. But it has a disadvantage that only the array can be emptied (0). If you want to set the array to a specific format CopyTo () The best way to change time in space.
There is only one point of view, the 2nd function call to the 3rd embedded algorithm, the efficiency is reduced. This can only be explained as a compiler optimization. It seems that using C # to write a program does not care too much about the overhead of function calls.
Application of the application of C # array initialization I'm going to explain to you here that I hope it will help you.