C# String Maniupulation with pointers performance?
I'm trying to do some testing with strings and I looked at this article: Is StringBuilder really faster than Aggreggate?
and I'm curious if pointers would gain any performance over the string builder object at all? The reason i'm asking is we have a windows service responsible for building reports and exporting the data into excel (using xml, not excel obje开发者_运维知识库cts of any kind), so the strings are very large for some of the reports. Using stringBuilder the service takes about 5 seconds to obtain the data from the DB, and 8 hrs to build the strings for the report. This is a co-workers code so I dont' have any examples right now to post but I'll see if I can't obtain some. Overall just curious if string building with pointers is faster than stringbuilder.
Thanks,
Chris
8 Hours? Must be a huge report. You could try and use a stream (http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx) instead of StringBuilder, since I think from your question you are writing it to a file anyways. I''m not sure of the implementaion, but Strinbuilder is probably spending a lot of time allocating more memory for your huge string, so its probably more efficient to just write it directly to a file stream.
It depends on the situation. The problem with strings is that they cannot be mutated. So any time you need to make a change, a new string is created and all the information will be copied to the new string. Stringbuilder works with an array, so when a character needs to change its real easy. But when data needs to be inserted the part behind the insertion needs to be moved and when the characters no longer fit in the array a whole new array needs to be created and the old data gets copied in.
That could be whats happeing, the array inside Stringbuilder keeps growing and old data needs to be copied in every time. For example, if there is space for 4 pages in the Stringbuilder, at some point the Stringbuilder needs to reserve space for (usally double) 8 pages, then needs to copy 4 pages of data.
This could be the reason for the excessive amount of time used.
If you use a stream instead, like Kratz said, the hardware will simply increase the allocated memory for your stream. Then there is no need to copy all the old data.
About the pointers: it would help if you know beforehand how much space you need, otherwise you would probably end up overwriting memory from another program. But if you know beforehand how much data you are going to use you can use it for the stringbuilder:
new System.Text.StringBuilder(amountOfCharsNeeded);
Edit: Using pointers like in C++ will effectively be the same as using StringBuilder in terms of memory usage and performance, only you will be managing the data yourself.
精彩评论