This document discusses optimizing C# code for speed, maintainability, and flexibility. It provides tips for using profilers to optimize for speed, establishing coding standards to improve maintainability, and refactoring code. Exceptions, allocation in loops, string concatenation, and validating enum values are discussed as examples of code that could be optimized. Guidelines are provided around using exceptions, GC.Collect, and designing enums.
8. Cyclomaticcomplexity The complexity M is then defined as: M = E - N + 2P Where E = the number of edges of the graph N = the number of nodes of the graph P = the number of connected components
9. Code refactoring Code refactoring is "disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior"
11. Exceptions Are they good? Try { conn.Close(); } catch (InvalidOperationException ex) { Console.WriteLine(ex.GetType().FullName); Console.WriteLine(ex.Message); } if (conn.State != ConnectionState.Closed) { conn.Close(); }
12. Guidelines: Exceptions Don’t Write unnecessary try-catch code Behavior is correct by default Rethrow using “throw e” Loses stack frame information Wrap in larger exception Unless you’re sure nobody would ever want to “look inside” Require an exception in a common path
13. What’s Wrong? public void TransmitResponse(ArrayList responses, StreamWriterstreamWriter) { foreach (DataResponse response in responses) { NetworkResponsenetworkResponse = response.GetNetwork(); networkResponse.Send(streamWriter); } GC.Collect(); // clean up temporary objects } 10
14. GC.Collect public void TransmitResponse(ArrayList responses, StreamWriterstreamWriter) { foreach (DataResponse response in responses) { NetworkResponsenetworkResponse = response.GetNetwork(); networkResponse.Send(streamWriter); } GC.Collect(); // clean up temporary objects }
15. Calling GC.Collect Bad because... Each collection has overhead Overhead not really related to # of “dead objects” Collecting one object is as expensive (roughly) as collecting one thousand Especially bad because... GC.Collect() does the most expensive collection
16. What’s Wrong? public override string ToString() { string fullString = ""; foreach (string s in strings) { fullString += s + " : "; } return fullString; } 10
17. Allocation in Loop public override string ToString() { string fullString = ""; foreach (string s in strings) { fullString += s + " : "; } return fullString; }
18. A better way public string ToString() { StringBuilder fullString = new StringBuilder(); foreach (string s in strings) { fullString.Append(s); fullString.Append(“:”); } return fullString.ToString(); }