Reputation: 642
I want to embed some precomputed data in a C# program. My current approach is to simply store the data in an array like so:
int[] someData = new int[] { 1, 2, 3, 4 };
My problem is the following: say someData contains 4kB of information. This 4kB is stored inside the executable and takes up memory. However, once the array initialization is executed the data is copied to the heap - doubling the space required. This is a waste as I will never write to this array so I could just as well get the data I want directly from the program binary.
Declaring the array as a readonly field does not help: that simply makes the array pointer readonly and does not prevent copying of the data (or writing to the array, for that matter). You cannot declare an array as const.
Is there any way I can prevent the copying and simply access the data directly from the program binary?
This is for a programming contest where the program is tested by running it thousands of times (by creating that many processes - my program is not given a neat file containing many test cases, it is executed once for each case). The array initialization takes up 90% of the time because the contents of the array have to be copied from the program executable to the heap. This seems like a waste of time so I want to find a way to avoid the copying and simply read the data directly from the program binary. What I am trying to accomplish is best represented like so (in pseudo-assembler):
jump to location 1002
...1000 words of data...
do a binary search on data from location 2 to 1001
Upvotes: 0
Views: 190
Reputation: 1503389
Is there any way I can prevent the copying and simply access the data directly from the program binary?
Instead of declaring it in the source code, use an embedded resource file, and read from it using Assembly.GetManifestResourceStream
. Given your comment on Damien's answer, this may still not be what you're looking for. You may want to use a memory mapped file instead... it's hard to know for sure.
Alternatively, you talk about the possibility of using a readonly variable - which sounds like it could be static too:
private static readonly int[] Data = { ... };
You raise the concern of the array contents being changed - but if you don't expose a way of writing to it, and you don't modify it yourself, you should be okay. What exactly are you concerned about? It feels like there's a lot of context here that you're not telling us.
Upvotes: 2
Reputation: 239814
No. There's no way to store an instance of an object in your program's executable. In order for you to access this data as an int[]
, that array object must be constructed. And that object must be constructed on one of the heaps (or placed on the stack, but not appropriate to this usage).
Are you really that concerned about 4k of space being wasted?
Upvotes: 0