SlideShare a Scribd company logo
Is Your C# Optimized? Woody Pewitt @woodyp woody@pewitt.org
What the heck is optimized C#?
Optimized For Speed Maintainability Flexibility etc…
You Want Speed? Visual Studio Profiler Third-party profilers System.Diagnostics
You Want Maintainability? Get a coding standard! Use A code metric Refactor RefactorRefactor!
Coding Standards Where do you get them?
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
Code refactoring Code refactoring is "disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior"
DXCore DevExpress http://www.devexpress.com/Products/Visual_Studio_Add-in/DXCore/ CodeRush and DXCore Community Plugins http://code.google.com/p/dxcorecommunityplugins/
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(); }
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
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
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 }
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
What’s Wrong? public override string ToString() {    string fullString = "";    foreach (string s in strings)    {       fullString += s + " : ";    }    return fullString; } 10
Allocation in Loop public override string ToString() {    string fullString = "";    foreach (string s in strings)    { fullString += s + " : ";    }    return fullString; }
A better way public string ToString() {    StringBuilder fullString = new StringBuilder();    foreach (string s in strings) { fullString.Append(s); fullString.Append(“:”);    }    return fullString.ToString(); }
What’s Wrong? enum ResponseType { ReturnValues, InvalidInput } string CreateWebText(string userInput, ResponseType operation) {    switch (operation) {       case ResponseType.ReturnValues:          userInput = "<h1>Values</h1>" + FilterOutBadStuff(userInput);          break;       case ResponseType.InvalidInput:          userInput = "<h1>Invalid</h1>" + FilterOutBadStuff(userInput);          break;    }    return userInput; } s = CreateWebText(s, (ResponseType) 133);  10
Checking – Method #1 string CreateWebText(string userInput, ResponseType operation) {    if (!Enum.IsDefined(typeof(ResponseType), operation)       throw new InvalidArgumentException(...);    switch (operation) {       case ResponseType.ReturnValues: userInput = "<h1>Values</h1>" + FilterOutBadStuff(userInput);          break;       case ResponseType.InvalidInput: userInput = "<h1>Invalid</h1>" + FilterOutBadStuff(userInput);          break;    }    return userInput; } enumResponseType {  ReturnValues,  InvalidInput, DumpValues, }
Checking – preferred string CreateWebText(string userInput, ResponseType operation) {    switch (operation) {       case ResponseType.ReturnValues: userInput = "<h1>Values</h1>" + FilterOutBadStuff(userInput);          break;       case ResponseType.InvalidInput: userInput = "<h1>Invalid</h1>" + FilterOutBadStuff(userInput);          break;       default:          throw new InvalidArgumentException(...);    }    return userInput; }
Guidelines: enums Don’t Assume that enums can only have defined values Assume that the set of defined values will never change
Questions? Woody Pewitt @woodyp woody@pewitt.org

More Related Content

What's hot

Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
Sumant Tambe
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
mohamed sikander
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
Knoldus Inc.
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
sajidpk92
 
c++ Lecture 2
c++ Lecture 2c++ Lecture 2
c++ Lecture 2
sajidpk92
 
What\'s New in C# 4.0
What\'s New in C# 4.0What\'s New in C# 4.0
What\'s New in C# 4.0
Eyal Vardi
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
OdessaJS Conf
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
Bartlomiej Filipek
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
Sardar Alam
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directives
Greg Bergé
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
Bob Tiernay
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
Brian Moschel
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
Rai University
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
OdessaJS Conf
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)
Ameer Hamxa
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
Matthieu Garrigues
 

What's hot (20)

Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Introduction to JQ
Introduction to JQIntroduction to JQ
Introduction to JQ
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
c++ Lecture 2
c++ Lecture 2c++ Lecture 2
c++ Lecture 2
 
What\'s New in C# 4.0
What\'s New in C# 4.0What\'s New in C# 4.0
What\'s New in C# 4.0
 
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
Operator Overloading
Operator Overloading  Operator Overloading
Operator Overloading
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directives
 
jq: JSON - Like a Boss
jq: JSON - Like a Bossjq: JSON - Like a Boss
jq: JSON - Like a Boss
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Mca 2nd sem u-4 operator overloading
Mca 2nd  sem u-4 operator overloadingMca 2nd  sem u-4 operator overloading
Mca 2nd sem u-4 operator overloading
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
 
c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)c++ pointers by Amir Hamza Khan (SZABISTIAN)
c++ pointers by Amir Hamza Khan (SZABISTIAN)
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 

Similar to Is your C# optimized

Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
Kevin Pilch
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
heinrich.wendel
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
Movel
 
PostThis
PostThisPostThis
PostThis
testingphase
 
Rx workshop
Rx workshopRx workshop
Rx workshop
Ryan Riley
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
Abed Bukhari
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
Sandeep Joshi
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
CodeOps Technologies LLP
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
LogeekNightUkraine
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
Jevgeni Kabanov
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
HCMUTE
 
Chapter 2
Chapter 2Chapter 2
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
Yaser Zhian
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
ppd1961
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
Paulo Morgado
 
C++ Function
C++ FunctionC++ Function
C++ Function
Hajar
 

Similar to Is your C# optimized (20)

Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
PostThis
PostThisPostThis
PostThis
 
Rx workshop
Rx workshopRx workshop
Rx workshop
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Effective Object Oriented Design in Cpp
Effective Object Oriented Design in CppEffective Object Oriented Design in Cpp
Effective Object Oriented Design in Cpp
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
 
Embedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for JavaEmbedded Typesafe Domain Specific Languages for Java
Embedded Typesafe Domain Specific Languages for Java
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
 
Whats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPontoWhats New In C# 4 0 - NetPonto
Whats New In C# 4 0 - NetPonto
 
C++ Function
C++ FunctionC++ Function
C++ Function
 

More from Woody Pewitt

Developing serverless applications with .NET on AWS
Developing serverless applications with .NET on AWSDeveloping serverless applications with .NET on AWS
Developing serverless applications with .NET on AWS
Woody Pewitt
 
Qcon sf - html5 cross-platform mobile solutions
Qcon sf - html5 cross-platform mobile solutionsQcon sf - html5 cross-platform mobile solutions
Qcon sf - html5 cross-platform mobile solutions
Woody Pewitt
 
Using html5 to build offline applications
Using html5 to build offline applicationsUsing html5 to build offline applications
Using html5 to build offline applications
Woody Pewitt
 
Super quick introduction to html5
Super quick introduction to html5Super quick introduction to html5
Super quick introduction to html5
Woody Pewitt
 
Technical debt
Technical debtTechnical debt
Technical debt
Woody Pewitt
 
From port 80 to applications
From port 80 to applicationsFrom port 80 to applications
From port 80 to applications
Woody Pewitt
 
Technical Debt
Technical DebtTechnical Debt
Technical Debt
Woody Pewitt
 
Mobile Web Best Practices
Mobile Web Best PracticesMobile Web Best Practices
Mobile Web Best Practices
Woody Pewitt
 
Internet protocalls & WCF/DReAM
Internet protocalls & WCF/DReAMInternet protocalls & WCF/DReAM
Internet protocalls & WCF/DReAM
Woody Pewitt
 
How To Create Web Sites For Mobile Clients
How To Create Web Sites For Mobile ClientsHow To Create Web Sites For Mobile Clients
How To Create Web Sites For Mobile Clients
Woody Pewitt
 
.Net Garbage Collector 101
.Net Garbage Collector 101.Net Garbage Collector 101
.Net Garbage Collector 101
Woody Pewitt
 
San Diego ASP.NET Meeting Oct 21st
San  Diego  ASP.NET Meeting Oct 21stSan  Diego  ASP.NET Meeting Oct 21st
San Diego ASP.NET Meeting Oct 21st
Woody Pewitt
 
San Diego Clound Computing Sep 9th
San Diego Clound Computing Sep 9thSan Diego Clound Computing Sep 9th
San Diego Clound Computing Sep 9th
Woody Pewitt
 

More from Woody Pewitt (13)

Developing serverless applications with .NET on AWS
Developing serverless applications with .NET on AWSDeveloping serverless applications with .NET on AWS
Developing serverless applications with .NET on AWS
 
Qcon sf - html5 cross-platform mobile solutions
Qcon sf - html5 cross-platform mobile solutionsQcon sf - html5 cross-platform mobile solutions
Qcon sf - html5 cross-platform mobile solutions
 
Using html5 to build offline applications
Using html5 to build offline applicationsUsing html5 to build offline applications
Using html5 to build offline applications
 
Super quick introduction to html5
Super quick introduction to html5Super quick introduction to html5
Super quick introduction to html5
 
Technical debt
Technical debtTechnical debt
Technical debt
 
From port 80 to applications
From port 80 to applicationsFrom port 80 to applications
From port 80 to applications
 
Technical Debt
Technical DebtTechnical Debt
Technical Debt
 
Mobile Web Best Practices
Mobile Web Best PracticesMobile Web Best Practices
Mobile Web Best Practices
 
Internet protocalls & WCF/DReAM
Internet protocalls & WCF/DReAMInternet protocalls & WCF/DReAM
Internet protocalls & WCF/DReAM
 
How To Create Web Sites For Mobile Clients
How To Create Web Sites For Mobile ClientsHow To Create Web Sites For Mobile Clients
How To Create Web Sites For Mobile Clients
 
.Net Garbage Collector 101
.Net Garbage Collector 101.Net Garbage Collector 101
.Net Garbage Collector 101
 
San Diego ASP.NET Meeting Oct 21st
San  Diego  ASP.NET Meeting Oct 21stSan  Diego  ASP.NET Meeting Oct 21st
San Diego ASP.NET Meeting Oct 21st
 
San Diego Clound Computing Sep 9th
San Diego Clound Computing Sep 9thSan Diego Clound Computing Sep 9th
San Diego Clound Computing Sep 9th
 

Recently uploaded

Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Jeffrey Haguewood
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
jpupo2018
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 

Recently uploaded (20)

Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Project Management Semester Long Project - Acuity
Project Management Semester Long Project - AcuityProject Management Semester Long Project - Acuity
Project Management Semester Long Project - Acuity
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 

Is your C# optimized

  • 1. Is Your C# Optimized? Woody Pewitt @woodyp woody@pewitt.org
  • 2.
  • 3. What the heck is optimized C#?
  • 4. Optimized For Speed Maintainability Flexibility etc…
  • 5. You Want Speed? Visual Studio Profiler Third-party profilers System.Diagnostics
  • 6. You Want Maintainability? Get a coding standard! Use A code metric Refactor RefactorRefactor!
  • 7. Coding Standards Where do you get them?
  • 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"
  • 10. DXCore DevExpress http://www.devexpress.com/Products/Visual_Studio_Add-in/DXCore/ CodeRush and DXCore Community Plugins http://code.google.com/p/dxcorecommunityplugins/
  • 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(); }
  • 19. What’s Wrong? enum ResponseType { ReturnValues, InvalidInput } string CreateWebText(string userInput, ResponseType operation) { switch (operation) { case ResponseType.ReturnValues: userInput = "<h1>Values</h1>" + FilterOutBadStuff(userInput); break; case ResponseType.InvalidInput: userInput = "<h1>Invalid</h1>" + FilterOutBadStuff(userInput); break; } return userInput; } s = CreateWebText(s, (ResponseType) 133); 10
  • 20. Checking – Method #1 string CreateWebText(string userInput, ResponseType operation) { if (!Enum.IsDefined(typeof(ResponseType), operation) throw new InvalidArgumentException(...); switch (operation) { case ResponseType.ReturnValues: userInput = "<h1>Values</h1>" + FilterOutBadStuff(userInput); break; case ResponseType.InvalidInput: userInput = "<h1>Invalid</h1>" + FilterOutBadStuff(userInput); break; } return userInput; } enumResponseType { ReturnValues, InvalidInput, DumpValues, }
  • 21. Checking – preferred string CreateWebText(string userInput, ResponseType operation) { switch (operation) { case ResponseType.ReturnValues: userInput = "<h1>Values</h1>" + FilterOutBadStuff(userInput); break; case ResponseType.InvalidInput: userInput = "<h1>Invalid</h1>" + FilterOutBadStuff(userInput); break; default: throw new InvalidArgumentException(...); } return userInput; }
  • 22. Guidelines: enums Don’t Assume that enums can only have defined values Assume that the set of defined values will never change
  • 23. Questions? Woody Pewitt @woodyp woody@pewitt.org

Editor's Notes

  1. Demo VS 2010 Profiler…
  2. http://duckduckgo.com/?q=.net%20coding%20standards&amp;kp=-1&amp;kn=1http://msdn.microsoft.com/en-us/library/czefa0ke(v=VS.71).aspx
  3. http://en.wikipedia.org/wiki/Code_refactoringhttp://c2.com/cgi/fullSearch - Ward Cunningham