Examples
Let's look at the initial version of the method. It runs four Replace calls on the formal parameter to the method. String literals are used as the argument. When looking at the string literals, you can see that they contain some common substrings: two contain "<span>C" and two contain "<span>D". This property can be used to optimize.First version of method [C#] static string A(string text) { text = text.Replace("<span>Cat ", "<span>Cats "); text = text.Replace("<span>Clear ", "<span>Clears "); text = text.Replace("<span>Dog ", "<span>Dogs "); text = text.Replace("<span>Draw ", "<span>Draws "); return text; } Second version of method [C#] static string B(string text) { if (text.Contains("<span>C")) { text = text.Replace("<span>Cat ", "<span>Cats "); text = text.Replace("<span>Clear ", "<span>Clears "); } if (text.Contains("<span>D")) { text = text.Replace("<span>Dog ", "<span>Dogs "); text = text.Replace("<span>Draw ", "<span>Draws "); } return text; }Second version. Now let's look at the optimized version. This version uses the Contains method around all the Replace calls with the specified common string literal. Thus, in version B, the first two Replace calls are only run when the common pattern is found; the second two Replace calls are also guarded.
Note:
Another approach would be to use text.Contains("<span>").
This could be beneficial depending on how common that string is in the hypothetical data set.
No comments:
Post a Comment