Hi all;
First off, this is for a .net 2.0 DLL that is usually called by a .NET 4.0+ app. (It is 2.0 because this is a commercial library and many are still on 2.0 - 3.5).
We have cases where we have a string or StringBuilder and need a substring from it. And in various places it is any of the 4 combinations (source = string or StringBuilder, new object = string or StringBuilder). The problem we have is our program is using a lot of memory and all the temporary strings that exist for about 4 instructions are making the grabage collector work a lot.
The best I have come up with is (our code isn't written this way, I'm just doing this to illustrate concisely:
string srcString = "thanks for the help";
StringBuilder srcStrBldr = new StringBuilder("thanks for the help");
- StringBuilder middle = new StringBuilder(srcStrBldr.ToString, 7, 7, 7);
- StringBuilder middle = new StringBuilder(srcString, 7, 7, 7);
- string middle = srcStrBldr.ToString().Substring(7, 7);
Questions:
- When running a .NET 4.0 app, is it still using the .NET 2.0 string class for the internals?
- Looking at the StringBuilder code via reflector shows that #1 will work great if the string was created in the same thread and the ArrayLength is short enough. However, running under VisualStudio, where it is a single threaded app, the StringBuilder.m_currentThread == 0 which does not match the current thread - and so a temp string is created. Any way around this? (I tried to get VisualStudio to step into this code - but couldn't make it happen - argh!)
- #2 above I think is fine.
- #3 above clearly creates a temp string.
Is there a better way to do this? If it is using the .NET 2.0 class, then being able to access StringBuilder.m_StringValue would let me write code for all of the above that does not create a temp string object. I could do that with reflection but that takes time which then puts me in the speed vs memory usage trade-off. And, what if the internal code changes (unlikely but possible).
So... any suggestions?
thanks - dave
What we did for the last 6 months - Made the world's coolest reporting & docgen system even more amazing