Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I speed up array cloning in C#?

I'm working on my solution to the Cult of the Bound Variable problem.

Part of the problem has you implement an interpreter for the "ancient" Universal Machine. I've implemented an intepreter for the machine they describe and now I'm running a benchmark program that the university provided to test it.

My C# implementation of this interpreter is slow!

I fired up my program in the ANTS profiler to see where the slowdown is and I can see that over 96% of my time is taken up by the "Load Program" operation.

ANTS Profile Results

The specification of this operator is as follows:

 #12. Load Program.

              The array identified by the B register is duplicated
              and the duplicate shall replace the '0' array,
              regardless of size. The execution finger is placed
              to indicate the platter of this array that is
              described by the offset given in C, where the value
              0 denotes the first platter, 1 the second, et
              cetera.

              The '0' array shall be the most sublime choice for
              loading, and shall be handled with the utmost
              velocity.

Here is my code for this operator:

case 12: // Load Program
    _platters[0] = (UInt32[])_platters[(int)_registers[B]].Clone();
    _finger = _registers[C];
    break;

The source code to my whole "Universal Machine" interpreter is here.

What can I do to make this faster? There are other implementations of this interpreter written in C which complete the entire benchmark significantly faster.

like image 512
mmcdole Avatar asked Jun 20 '11 22:06

mmcdole


People also ask

How do I clone an array?

You can use a for loop and copy elements of one to another one by one. Use the clone method to clone an array. Use arraycopy() method of System class. Use copyOf() or copyOfRange() methods of Arrays class.

Are arrays fast?

An array is faster and that is because ArrayList uses a fixed amount of array. However when you add an element to the ArrayList and it overflows. It creates a new Array and copies every element from the old one to the new one.


3 Answers

You could try using Buffer.BlockCopy, although I'd be surprised if it makes any massive difference in this case:

case 12: // Load Program
    uint[] src = _platters[(int)_registers[B]];
    _platters[0] = new uint[src.Length];
    Buffer.BlockCopy(src, 0, _platters[0], 0, src.Length * 4);
    _finger = _registers[C];
    break;
like image 155
LukeH Avatar answered Nov 02 '22 18:11

LukeH


Buffer.BlockCopy promises to be much faster, as per this MSDN thread.

like image 28
Anton Gogolev Avatar answered Nov 02 '22 18:11

Anton Gogolev


Use the BlockCopy method described here: http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/42189513-2106-4467-af9a-3b1810509cc8/

like image 26
Ed Bayiates Avatar answered Nov 02 '22 20:11

Ed Bayiates