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

What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
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
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
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
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
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
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Precisely
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 

Recently uploaded (20)

What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
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
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
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
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
TrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc Webinar - 2024 Global Privacy Survey
TrustArc Webinar - 2024 Global Privacy Survey
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their MainframeDigital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
Digital Banking in the Cloud: How Citizens Bank Unlocked Their Mainframe
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 

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