I am writing a code where it reads Messages from MCU, and stores them in an array of 8 bytes[0]~[7], specifically storing the first 4 values in the first half[0] ~[3] and the next four values in the next half[4] ~[7], Is there any way to bind the two for loops into one for loop, coz I have to run 7 cases in the switch with 2 for loops in each, all the for loops has the same syntax.
halfbytelength = 4;
bytelength =8;
case 0:
for (index = 0; index <halfbytelength; index = 1)
{
Array1[index] = msg[index];
}
for (index = halfbytelength; index < bytelength; index = 1)
{
Array2[index - halfbytelength] = msg[index];
}
MainArray[0] = ASCIIEncoding.ASCII.GetString(Array1);
MainArray[1] = ASCIIEncoding.ASCII.GetString(Array2);
CodePudding user response:
Assuming that bytelength
stays even, you can do the following to replace your 2 loops with 1:
for (int index = 0; index < halfbytelength; index)
{
Array1[index] = msg[index];
Array2[index] = msg[index halfbytelength];
}
Note: as @JeremyLakeman commented below, using Array.Copy
might be faster.
Your code will also be shorter (1 line per array, with no loops).
(assuming that msg
,Array1
,Array2
are of array type - which you didn't specify in your question).
CodePudding user response:
There should be no need to write the loop to copy bytes yourself. You for example use spans to slice the array.
var array1 = msg.AsSpan().Slice(0, 4).ToArray();
var array2 = msg.AsSpan().Slice(4, 8).ToArray();
I would say that it is significantly easier to read. Or add an extension method to convert a span to string directly.
Or you could use Array.Copy
Array.Copy(msg, 0, array1, 0, 4);
Array.Copy(msg, 4, array2, 0, 4);
But I find that less easy to read.
With regards to performance I would not expect a huge difference. I would expect converting the array to a string to take more time than copying a few bytes. But any method that avoid allocations might have some advantage if it is run in a tight loop.