SlideShare una empresa de Scribd logo
1 de 3
Basics for performance improvement in Entity
Framework using LINQ
1. Remove all for each loops for accessing and manipulating data using entity
framework. Instead use LINQ to SQL/ENTITIES.
a. LINQ though adds slight additional overhead over for each loop when dealing
with very large amount of data.
b. But LINQ to SQL or Entity framework has a better performance as LINQ
query gets directly converted to T-SQL.
c. LINQ provides shorter better readable and maintainable code.
d. Basic facts –
i. LINQ gets executed when it gets enumerated by foreach loop.
ii. LINQ gets executed by collection operations like ToArray(), ToList(),
ToDictionary().

2. Disable change tracking for entity if not needed.
a. Whenever we are only reading data (no modification involved) then we should
disable tracking of changes to entity.
b. This prevents unnecessary entity caching and management.
unitResponse = (from unitRow in entities.Units.AsNoTracking()
where unitRow.UnitID == unitId
selectnew PocoEntities.Unit()
{
ID = unitRow.UnitID,
Level = unitRow.Level,
Theme = unitRow.Theme
});

3. Avoid fetching fields that are not required.
a. For example I want to get only unit id, level and theme fields of the Unit table
from DB.
b. So I fetch only those fields in my LINQ query instead of selecting the entire
unitRow variable in the query.
unitResponse = (fromunitRowin entities.Units.AsNoTracking()
where unitRow.UnitID == unitId
selectnew PocoEntities.Unit()
{
ID = unitRow.UnitID,
Level = unitRow.Level,
Theme = unitRow.Theme
});

4. Try to write LINQ in such a way that there is a single round trip while executing the
query.
a. Code with multiple round trips.
foreach (Customer c in Customers)
foreach (Purchase p in c.Purchases)
// Another SQL round-trip
Console.WriteLine (c.Name + " spent " + p.Price);

b. Code with single round trip.
from c in Customers
select
from p in c.Purchases
selectnew { c.Name, p.Price }

5. Avoid using Contains.
a. When using LINQ to SQL avoid using contains.
b. This gets converted to WHERE IN clause in SQL. This leads to performance
degrades with large data sets.
c. In WHERE IN sub query gets executed first, the result is indexed and made
distinct.The output is then joined tofirst part of the query.
d. But at the same time we can use Contains in LINQ to entities.

6. For filtering data use DataLoadOptions.
a. DataLoadOptions in LINQ allows immediate loading and filtering of related
data. It allows you load related objects so this removes the need for firing a
sub query every time you ask for related objects.
b. If you have written code like below then each time inner loop fires a query on
DB. This in turn decreases performance.
foreach (Customer c in Customers)
{
Console.WriteLine (c.ID + " " + c.Name);
foreach (Purchase p in c.Purchases)
Console.WriteLine (" - purchased a " + p.Description);
}

c. Using DataLoadOptions loadrelated objects.
var options = new DataLoadOptions();
options.AssociateWith <Customer> (c => c.Purchases.Where (p => p.Price
>1000));
LoadOptions = options;
foreach (Customer c in Customers)
{
Console.WriteLine (c.ID + " " + c.Name);
foreach (Purchase p in c.Purchases)
Console.WriteLine ("

- purchased a " + p.Description);

}

7. Eager loading means immediate loading of all the related objects when you query for
an object.This can be done in two ways:a. DataLoadOptions (LINQ to SQL) – This creates a single SQL query for
querying two related tables.
var options = new DataLoadOptions();
options.LoadWith <Customer> (c => c.Purchases);
LoadOptions = options;
foreach (Customer c in Customers)
{
Console.WriteLine (c.ID + " " + c.Name);
foreach (Purchase p in c.Purchases)
Console.WriteLine (" - purchased a " + p.Description);
}

b. Using include method (LINQ to Entity framework) –This creates a single
query for related objects by using a SQL join.
List<Customer> customers = db.Customer.Include("Purchases").ToList();

8. In order to debug and optimize LINQ queries I used the below two mentioned tools:a. LINQPad – This helps us execute and debug LINQ queries. It also helps us in
converting the LINQ queries to SQL queries. This way we can validate the
performance of our LINQ query.
b. Linqer – This helps us in converting our SQL queries to LINQ. So we can
write our own optimized SQL queries and convert them to LINQ.

9. Areas to explore :a. Use Pre-Generating Views to reduce response time for first request.
b. Use Compiled Query wherever needed.

http://ankushasthana.blogspot.jp/2014/02/basics-for-performance-improvement-in.html.

Más contenido relacionado

Último

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 

Destacado

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Destacado (20)

AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 
ChatGPT webinar slides
ChatGPT webinar slidesChatGPT webinar slides
ChatGPT webinar slides
 
More than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike RoutesMore than Just Lines on a Map: Best Practices for U.S Bike Routes
More than Just Lines on a Map: Best Practices for U.S Bike Routes
 

Basics for performance improvement of Entity Framework using LINQ

  • 1. Basics for performance improvement in Entity Framework using LINQ 1. Remove all for each loops for accessing and manipulating data using entity framework. Instead use LINQ to SQL/ENTITIES. a. LINQ though adds slight additional overhead over for each loop when dealing with very large amount of data. b. But LINQ to SQL or Entity framework has a better performance as LINQ query gets directly converted to T-SQL. c. LINQ provides shorter better readable and maintainable code. d. Basic facts – i. LINQ gets executed when it gets enumerated by foreach loop. ii. LINQ gets executed by collection operations like ToArray(), ToList(), ToDictionary(). 2. Disable change tracking for entity if not needed. a. Whenever we are only reading data (no modification involved) then we should disable tracking of changes to entity. b. This prevents unnecessary entity caching and management. unitResponse = (from unitRow in entities.Units.AsNoTracking() where unitRow.UnitID == unitId selectnew PocoEntities.Unit() { ID = unitRow.UnitID, Level = unitRow.Level, Theme = unitRow.Theme }); 3. Avoid fetching fields that are not required. a. For example I want to get only unit id, level and theme fields of the Unit table from DB. b. So I fetch only those fields in my LINQ query instead of selecting the entire unitRow variable in the query. unitResponse = (fromunitRowin entities.Units.AsNoTracking() where unitRow.UnitID == unitId selectnew PocoEntities.Unit() { ID = unitRow.UnitID, Level = unitRow.Level, Theme = unitRow.Theme
  • 2. }); 4. Try to write LINQ in such a way that there is a single round trip while executing the query. a. Code with multiple round trips. foreach (Customer c in Customers) foreach (Purchase p in c.Purchases) // Another SQL round-trip Console.WriteLine (c.Name + " spent " + p.Price); b. Code with single round trip. from c in Customers select from p in c.Purchases selectnew { c.Name, p.Price } 5. Avoid using Contains. a. When using LINQ to SQL avoid using contains. b. This gets converted to WHERE IN clause in SQL. This leads to performance degrades with large data sets. c. In WHERE IN sub query gets executed first, the result is indexed and made distinct.The output is then joined tofirst part of the query. d. But at the same time we can use Contains in LINQ to entities. 6. For filtering data use DataLoadOptions. a. DataLoadOptions in LINQ allows immediate loading and filtering of related data. It allows you load related objects so this removes the need for firing a sub query every time you ask for related objects. b. If you have written code like below then each time inner loop fires a query on DB. This in turn decreases performance. foreach (Customer c in Customers) { Console.WriteLine (c.ID + " " + c.Name); foreach (Purchase p in c.Purchases) Console.WriteLine (" - purchased a " + p.Description); } c. Using DataLoadOptions loadrelated objects. var options = new DataLoadOptions(); options.AssociateWith <Customer> (c => c.Purchases.Where (p => p.Price >1000)); LoadOptions = options; foreach (Customer c in Customers) { Console.WriteLine (c.ID + " " + c.Name); foreach (Purchase p in c.Purchases)
  • 3. Console.WriteLine (" - purchased a " + p.Description); } 7. Eager loading means immediate loading of all the related objects when you query for an object.This can be done in two ways:a. DataLoadOptions (LINQ to SQL) – This creates a single SQL query for querying two related tables. var options = new DataLoadOptions(); options.LoadWith <Customer> (c => c.Purchases); LoadOptions = options; foreach (Customer c in Customers) { Console.WriteLine (c.ID + " " + c.Name); foreach (Purchase p in c.Purchases) Console.WriteLine (" - purchased a " + p.Description); } b. Using include method (LINQ to Entity framework) –This creates a single query for related objects by using a SQL join. List<Customer> customers = db.Customer.Include("Purchases").ToList(); 8. In order to debug and optimize LINQ queries I used the below two mentioned tools:a. LINQPad – This helps us execute and debug LINQ queries. It also helps us in converting the LINQ queries to SQL queries. This way we can validate the performance of our LINQ query. b. Linqer – This helps us in converting our SQL queries to LINQ. So we can write our own optimized SQL queries and convert them to LINQ. 9. Areas to explore :a. Use Pre-Generating Views to reduce response time for first request. b. Use Compiled Query wherever needed. http://ankushasthana.blogspot.jp/2014/02/basics-for-performance-improvement-in.html.