A string assignment efficiency question

Rawblues

New member
Joined
Feb 15, 2006
Messages
2
Location
Bath, UK
Programming Experience
10+
Teaching myself VB .NET, and the solution to this one is not obvious to me, but you guys can probably answer it pronto.

I've got a string of several thousand bytes in length, and I want to be able to replace characters anywhere within the string by absolute position. I'll always be replacing characters by exactly the same number of characters so methods to remove/insert etc are not appropriate.

i.e.

(lots of bytes..).........abcdefg.........(..lots of bytes)
becomes
(lots of bytes..).........abxyzfg.........(..lots of bytes)

I am going to want to do it thousands of times, so I want a solution that's very efficient, just altering the values of existing bytes in memory without any reallocation etc

What are my options?
 
Using an actual String object would be the least efficient way. Using a StringBuilder object would be more efficient. If you aren't changing the number of characters then you could also convert to a Char array and alter individual Char objects. The most efficient would be to write a DLL in C# and use unsafe code, which supports pointers. I believe that you may be able to get at the memory directly using the Marshal class, but I can't tell you the details. I'm sure if it's possible then it's messy as VB was never really designed for things particularly low-level.
 
Thanks

..to jmcilhinney

Your answer confirms that I wasn't being totally stupid, then. I'll try the char array approach and see how that goes. Looks like the C# route might be more flexible for real life situations...

..to gazeranco

This is the kind of thing that you often want to be able to do. When I coded up the obvious solution to my problem using string concatenation etc, the performance was so crap as to be unusable (on a 2.6GHz m/c + 512Mb RAM), hence the question.
 
Back
Top