Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Most efficient way to replace placeholders text with actual values?

Tags:

.net

replace

I've a a template text (a newsletter text) to be sent to many users; in the text there are some placeholders, such as {{firstname}}, {{lastname}} and so on.

What would be more efficient for replacing placeholders with actual values, .Replace(..) concatenation or RegExp, or other methods?

.NET language.

like image 570
ʞᴉɯ Avatar asked Apr 15 '13 20:04

ʞᴉɯ


2 Answers

Since you will be calling .Replace() multiple times, it's probably more efficient to use StringBuilder.Replace(), since StringBuilder is optimized for multiple modifications.

If you have flexibility in the format of the placeholders, I think DotLiquid would be a good candidate for this. They probably have optimized the text processing for this scenario, although it also supports other advanced syntax so there might be overhead there.

like image 164
AaronLS Avatar answered Nov 09 '22 21:11

AaronLS


I recently test-compared standard dotnet ways

  1. string.Replace.Replace.Replace - least memory efficient but slightly quicker than StringBuilder

  2. StringBuilder.Replace.Replace.Replace 2x times memory efficient to string.Replace but a bit slower

  3. string.Format("{0},{1},{2}", x, y, z) is about 20% less memory efficient vs StringBuilder but 2x+ quicker than string.Replace.Replace.Replace

like image 23
T.S. Avatar answered Nov 09 '22 19:11

T.S.