I’m passing a map of strings from native c++ class to c# using c++/CLI. Native code using stl map. In C++/CLI I convert each stl string to CString and insert to a Dictionary^ using String^ str = gcnew String(umngd.c_str()).
Apart from the need to iterate the map which I wonder if there is a built in way to do, my problem is that this piece of code a very slow probably due to the many gcnew discrete memory allocations. My question is how do I preallocate all needed memory and then insert the values into this preallocated memory.
Thank you.
gcnew creates an instance of a managed type on the garbage collected heap. The .NET CLR already preallocates space for the heap and manages its size, and it’s pretty smart about it.
You cannot preallocate managed objects. If you want a million managed string objects, you’ll need a million gcnew’s. On my laptop, this takes a few hundred milliseconds. Is this too slow?
Test your code. If it’s actually too slow, maybe you can use a different approach. There’s a bit of discussion of alternatives here.