String.Concat usage / abuse detection tool (where StringBuilder should be used)

It is well known that instead of a small number of concatenations you should not use StringBuilder:

string s = "Hello"; if (greetingWorld) { s += " World"; } s += "!"; 

However, in significant size loops, StringBuilder is the obvious choice:

 string s = ""; foreach (var i in Enumerable.Range(1,5000)) { s += i.ToString(); // <- bad idea! } Console.WriteLine(s); 

Is there a tool that I can run either on the original C # source source or on a compiled assembly to identify where in the source code String.Concat is String.Concat ? (If you are not familiar, s += "foo" maps to String.Concat in the output of IL). Obviously, I cannot realistically search the entire project and evaluate each += to determine if the value of l is a string value.

Ideally, it will only point to calls inside the for / foreach loop, but I would even allow all the false positives to String.Concat every String.Concat . In addition, I know that there are some refactoring tools that automatically reorganize my code to use StringBuilder , but I'm only interested in identifying the use of Concat at this point.

I regularly run the gendarme and FxCop in my code, and none of these tools define what I described. However, as @Cristian noted, older versions of FxCop used to test this. Maybe there is a way to extract this rule from the old version of FxCop and report a newer version (1.36) to use it?

+4
source share
2 answers

Perhaps NDepend CQL (code query language) is expressive enough for this. Not sure if this is true.

+3
source

FxCop had some tips for this. Check out this article

For example, according to an article in this code:

 static string BadConcatenate(string[] items) { string strRet = string.Empty; foreach(string item in items) { strRet += item; } return strRet; } 

FxCop Reports

 "Change StringCompareTest.BadConcatenate(String[]):String to use StringBuilder instead of String.Concat or + 

Edit

It appears that rule CA1807 has been removed either due to the high noise level or due to a lack of analysis. And it seems that the compiler does not replace it automatically , in the same link they describe in more detail the performance of both methods.

0
source

Source: https://habr.com/ru/post/1309338/


All Articles