2
\$\begingroup\$

Q1: What are the benefits of using any external library e.g Antlr3.StringTemplate?

Q2: What are the potential issues with the below implementation?

public class StringTemplate
{
    private string text = string.Empty;
    public StringTemplate(string template)
    {
        this.text = template;
    }

    public StringTemplate SetAttribute(string attribute, object value)
    {
        text = text.Replace($"${attribute}$", value?.ToString() ?? "");
        return this;
    }
    public override string ToString()
    {
        return text.ToString();
    }
}

And use it like below

 private void writeMsg()
 {
     var email = "Dear $name$...";//Loading from html file place holder used pattern $placeholder$.

     var template =
         new StringTemplate(email)
         .SetAttribute("name", "John");

     Console.WriteLine(template.ToString());
 }
\$\endgroup\$
1
\$\begingroup\$

One probable issue is performance, suppose there are 30 tokens to be replaced. And email template has a size of 50 kb. strings are immutable in C#/.Net. That means whenever you call StringTemplate.SetAttribute it creates a new string by manipulating existing and return the new string. suppose there are 30 tokens so it will create 50KB * 29 waste string. It will create more pressure on GC and GC will collect more often which will lead to poor performance. Better to use List<char> to do this kind of operation.

\$\endgroup\$
  • \$\begingroup\$ Can you paste some code samples? It would be more helpful. \$\endgroup\$ – Siraj M Nov 15 '19 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.