开发者

Remove vs New Instance

开发者 https://www.devze.com 2023-01-26 06:40 出处:网络
I\'m wondering what a better practice is in general .NET programming with class instances that contain a Remove method.

I'm wondering what a better practice is in general .NET programming with class instances that contain a Remove method.

The question is: if I have a StringBuilder sb with some data, is it smarter to use the .Remove(0, sb.Length) or to create a new instance and leave the old to the GC to collect. There are quite a few factors tha开发者_StackOverflow社区t I am aware of so I would like to know your opinions on this one.

Thanks,

Sanjin


In general, create a new one.

The .NET memory system is geared toward creating and de-allocating lots of small, short-lived objects quickly. StringBuilder.Remove() is likely to be slower.

For very large data (over 80kB) the rules change a little, depending on lots of factors.


I would definitely go for creating a new instance until a profiler has shown that this is the most critical part of your application.

This micro optimization kind of reuse just confuses any readers about the intent of the code.


Don't use .Remove(0, sb.Length) use .Clear() instead. It's easier to read and if Remove hasn't been optimized for this special use-case Clear will be faster too.
Or just allocate a new StringBuilder. The StringBuilder itself it lightweight, so I don't think using a new one will be expensive.
I usually wouldn't distinguish Clear() and allocating a new StringBuilder based on performance benefits of one, but on which creates the better readable code. And that depends on your use-case. Don't micro optimize unless you're profiler has shown that it's necessary.
In my experience you allocate a new StringBuilder at the beginning of some method and only call ToString when producing the return-value of the function. In that case it's stupid to complicate the function interface just to reuse a StringBuilder.

And I think when you call ToString() the StringBuilder gives out it's internal, so the internal buffer becomes immutable and StringBuilder needs to allocate a new on the next change one anyways.

One micro-optimization that can be useful is passing in a capacity to the constructor of a StringBuilder, if you know exactly(or at least a lower bound on) how long the result will be. Then it doesn't have to grow the array in multiple steps. For example if you know that the output will be at least 10000 characters you can init the builder to a capacity of 10000.

0

精彩评论

暂无评论...
验证码 换一张
取 消