ʞᴉɯ
ʞᴉɯ

Reputation: 5594

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

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.

Upvotes: 6

Views: 1158

Answers (2)

T.S.
T.S.

Reputation: 19384

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

Upvotes: 1

AaronLS
AaronLS

Reputation: 38394

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.

Upvotes: 3

Related Questions