Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting subarray as reference in C#

Tags:

arrays

c#

I have a large number of functions accepting input of sub-arrays (let's say, string) in a read-only way.

I used Array.Copy (C++ memmove equivalent from MSDN) as a temporary workaround, but it comes to a serious bottleneck on running speed. Is there any function I can get a sub-array, let's say [4~94] inside [0~99], such that it can be passed to a function x(array[]) as a reference where inside x the array is defined by [0~90]?

like image 698
orb Avatar asked Mar 16 '15 02:03

orb


1 Answers

Unfortunately, arrays don't play nicely with partitioning. The only way to get a sub-array is by creating a copy of the original array, which is where the bottleneck probably is.

If you can modify your functions to take IEnumerable parameters instead of arrays, you can do this easily with LINQ:

string[] values = { "foo", "bar", "baz", "zap" };
IEnumerable<string> subset = values.Skip(1).Take(2);

You could also look into ArraySegment, but this would (again) require changes to your functions' parameter types.

string[] values = { "foo", "bar", "baz", "zap" };
ArraySegment<string> segment = new ArraySegment<string>(values, 1, 2);
like image 95
BJ Myers Avatar answered Sep 29 '22 06:09

BJ Myers