SlideShare a Scribd company logo
1 of 26
Download to read offline
Symfony2 performance issues and improvements
Symfony2 performance
issues and improvements
Vitaliy Berdylo
vberdylo@orocrm.com
https://github.com/vitaliyberdylo
Symfony2 performance issues and improvements
WHAT is Performance
- Server response time
- Render response time
Symfony2 performance issues and improvements
Premature optimization
Symfony2 performance issues and improvements
Measure performance
Symfony2 performance issues and improvements
Measure serverside performance
Backend benchmarks:
- ab ApacheBanch
- siege
Profiler:
- XHProf + XHGui
- Blackfire
Enable the slow query log
Symfony2 performance issues and improvements
Measure client performance
Client benchmark:
- YSlow
- PageSpeed
online:
https://gtmetrix.com/
http://www.webpagetest.org/
Symfony2 performance issues and improvements
Symfony book Performance
- Use a Byte Code Cache (e.g. APC)
- Use Composer's Class Map Functionality
- Caching the Autoloader with APC
- Use Bootstrap Files
Symfony2 performance issues and improvements
Expensive service construction
- Be careful with listeners for kernel.request, kernel.
controller, kernel.view and kernel.response events.
- Don't perform any work in the service constructor
- Minimize deep layers of dependencies
- Minimize injecting services into listeners
- Use lazy services
Symfony2 performance issues and improvements
kernel.request event issues
- Avoid calling a database or external services in listeners
- Don’t forget check request type and skip listener run for sub-requests
- Avoid excessive usage of Internal Subrequests. Every sub-request will
go through the HttpKernel event lifecycle.
use SymfonyComponentHttpKernelEventGetResponseEvent;
// ...
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
// don't do anything if it's not the master request
return;
}
// ...
}
Symfony2 performance issues and improvements
User don’t need wait
Symfony2 performance issues and improvements
Do blocking work in the background
Symfony2 performance issues and improvements
Doctrine best practice
- Constrain relationships as much as possible. Avoid bidirectional
associations if possible
- Avoid composite keys
- Use lifecycle events judiciously
-Make $em->clear() in batches
$batchSize = 20;
for ($i = 1; $i <= 10000; ++$i) {
$user = new User;
$user->setStatus('user');
$user->setUsername('user' . $i);
$user->setName('Mr.Smith-' . $i);
$em->persist($user);
if (($i % $batchSize) === 0) {
$em->flush();
$em->clear(); // Detaches all objects from Doctrine!
}
}
$em->flush(); //Persist objects that did not make up an entire batch
$em->clear();
Symfony2 performance issues and improvements
Enable doctrine cache
doctrine:
orm:
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
Symfony2 performance issues and improvements
Enable doctrine cache
You can use your own service:
doctrine:
orm:
metadata_cache_driver: apc
result_cache_driver: apc
query_cache_driver: apc
doctrine:
orm:
metadata_cache_driver:
type: service
id: acme.demo.doctrine.cache.mycache
// ...
Symfony2 performance issues and improvements
Custom caching service
<?php
namespace AcmeDemoBundleDoctrineCache;
use DoctrineCommonCacheCacheProvider
class MyCache extends CacheProvider
{
protected function doFetch($id) {}
protected function doContains($id) {}
protected function doSave($id, $data, $lifeTime = 0) {}
protected function doDelete($id) {}
protected function doFlush() {}
protected function doGetStats() {}
}
Symfony2 performance issues and improvements
Caching in action
/**
* Get all articles with best rank
* @return array
*/
public function findBestArticles()
{
$query = $this->createQueryBuilder('article')
->select('article.title, article.description, article.published')
->where('article:rank = :rank')
->orderBy('article.published')
->setParameter('rank', 5)
->getQuery();
$query->useResultCache(
true,
3600,
__METHOD__ . serialize($query->getParameters())
);
$query->useQueryCache(true);
return $query->getArrayResult();
}
Symfony2 performance issues and improvements
Beware of lazy loading
Symfony2 performance issues and improvements
Beware of lazy loading
Beware of lazy loading when querying entities with associations
{% for article in articles %}
<article>
<h2>{{ article.title }}</h2>
<p>Author: {{ article.author.firstName }} {{ article.author.lastName }}</p>
<p>{{ article.text }}</p>
</article>
{% endfor %}
Symfony2 performance issues and improvements
Beware of lazy loading
Beware of lazy loading when querying entities with associations
Apparent solution:
{% for article in articles %}
<article>
<h2>{{ article.title }}</h2>
<p>Author: {{ article.author.firstName }} {{ article.author.lastName }}</p>
<p>{{ article.text }}</p>
</article>
{% endfor %}
$articles = $this->getDoctrine()->getRepository('AcmeDemoBundle:Article')->findAll();
Symfony2 performance issues and improvements
Beware of lazy loading
Right solution:
// src/Acme/DemoBundle/Entity/Repository/ArticleRepository
public function findAllWithAuthors()
{
$qb = $this->createQueryBuilder('article');
$qb->addSelect('author')
->innerJoin('article.author', 'author');
return $qb->getQuery()->getResult();
}
Symfony2 performance issues and improvements
Don't use hydration without needs
Doctrine ORM, like most ORMs, is performing a process called Hydration
when converting database results into objects.
With hydration:
Without hydration
$articles = $this->createQueryBuilder('article')->getQuery()->getResult();
$articles = $this->createQueryBuilder('article')->getQuery()->getResult(Query::HYDRATE_ARRAY);
$articles = $this->createQueryBuilder('article')->getQuery()->getArrayResult();
Symfony2 performance issues and improvements
Use Reference Proxies
With get author query into DB:
Without query for getting author:
$author = $this->getDoctrine()
->getManagerForClass('AcmeDemoBundle:Article')
->getRepository('AcmeDemoBundle:Article')->find($authorId);
$article = new Article();
$article->setAuthor($author);
$em = $this->getDoctrine()->getManagerForClass('AcmeDemoBundle:Article');
$article = new Article();
$article->setAuthor($em->getReference('AcmeDemoBundle:Author', $authorId));
Symfony2 performance issues and improvements
Assets
- Merging and minifying assets with Assetic (YUI compressor)
- CSS at top javascript at bottom
- use sprites for images
- encode small images into base64
- run image optimizations on your images
Symfony2 performance issues and improvements
Use reverse proxy
Symfony2 performance issues and improvements
Bibliography
● http://blog.hma-info.
de/content/stuff/Full_Stack_Web_Application_Performance_Tuning.pdf
● http://symfony.com/blog/push-it-to-the-limits-symfony2-for-high-
performance-needs
● https://tideways.io/profiler/blog/5-ways-to-optimize-symfony-baseline-
performance
● http://ocramius.github.io/blog/doctrine-orm-optimization-hydration
● http://labs.octivi.com/mastering-symfony2-performance-internals
● http://www.emanueleminotto.it/im-afraid-symfony-2-performances
● http://alexandre-salome.fr/media/sfpot-english.pdf
Symfony2 performance issues and improvements
Questions & Answers

More Related Content

Recently uploaded

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Recently uploaded (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

Featured

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
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
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
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...
 

Symfony2 performance issues and improvements

  • 1. Symfony2 performance issues and improvements Symfony2 performance issues and improvements Vitaliy Berdylo vberdylo@orocrm.com https://github.com/vitaliyberdylo
  • 2. Symfony2 performance issues and improvements WHAT is Performance - Server response time - Render response time
  • 3. Symfony2 performance issues and improvements Premature optimization
  • 4. Symfony2 performance issues and improvements Measure performance
  • 5. Symfony2 performance issues and improvements Measure serverside performance Backend benchmarks: - ab ApacheBanch - siege Profiler: - XHProf + XHGui - Blackfire Enable the slow query log
  • 6. Symfony2 performance issues and improvements Measure client performance Client benchmark: - YSlow - PageSpeed online: https://gtmetrix.com/ http://www.webpagetest.org/
  • 7. Symfony2 performance issues and improvements Symfony book Performance - Use a Byte Code Cache (e.g. APC) - Use Composer's Class Map Functionality - Caching the Autoloader with APC - Use Bootstrap Files
  • 8. Symfony2 performance issues and improvements Expensive service construction - Be careful with listeners for kernel.request, kernel. controller, kernel.view and kernel.response events. - Don't perform any work in the service constructor - Minimize deep layers of dependencies - Minimize injecting services into listeners - Use lazy services
  • 9. Symfony2 performance issues and improvements kernel.request event issues - Avoid calling a database or external services in listeners - Don’t forget check request type and skip listener run for sub-requests - Avoid excessive usage of Internal Subrequests. Every sub-request will go through the HttpKernel event lifecycle. use SymfonyComponentHttpKernelEventGetResponseEvent; // ... public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { // don't do anything if it's not the master request return; } // ... }
  • 10. Symfony2 performance issues and improvements User don’t need wait
  • 11. Symfony2 performance issues and improvements Do blocking work in the background
  • 12. Symfony2 performance issues and improvements Doctrine best practice - Constrain relationships as much as possible. Avoid bidirectional associations if possible - Avoid composite keys - Use lifecycle events judiciously -Make $em->clear() in batches $batchSize = 20; for ($i = 1; $i <= 10000; ++$i) { $user = new User; $user->setStatus('user'); $user->setUsername('user' . $i); $user->setName('Mr.Smith-' . $i); $em->persist($user); if (($i % $batchSize) === 0) { $em->flush(); $em->clear(); // Detaches all objects from Doctrine! } } $em->flush(); //Persist objects that did not make up an entire batch $em->clear();
  • 13. Symfony2 performance issues and improvements Enable doctrine cache doctrine: orm: metadata_cache_driver: apc result_cache_driver: apc query_cache_driver: apc
  • 14. Symfony2 performance issues and improvements Enable doctrine cache You can use your own service: doctrine: orm: metadata_cache_driver: apc result_cache_driver: apc query_cache_driver: apc doctrine: orm: metadata_cache_driver: type: service id: acme.demo.doctrine.cache.mycache // ...
  • 15. Symfony2 performance issues and improvements Custom caching service <?php namespace AcmeDemoBundleDoctrineCache; use DoctrineCommonCacheCacheProvider class MyCache extends CacheProvider { protected function doFetch($id) {} protected function doContains($id) {} protected function doSave($id, $data, $lifeTime = 0) {} protected function doDelete($id) {} protected function doFlush() {} protected function doGetStats() {} }
  • 16. Symfony2 performance issues and improvements Caching in action /** * Get all articles with best rank * @return array */ public function findBestArticles() { $query = $this->createQueryBuilder('article') ->select('article.title, article.description, article.published') ->where('article:rank = :rank') ->orderBy('article.published') ->setParameter('rank', 5) ->getQuery(); $query->useResultCache( true, 3600, __METHOD__ . serialize($query->getParameters()) ); $query->useQueryCache(true); return $query->getArrayResult(); }
  • 17. Symfony2 performance issues and improvements Beware of lazy loading
  • 18. Symfony2 performance issues and improvements Beware of lazy loading Beware of lazy loading when querying entities with associations {% for article in articles %} <article> <h2>{{ article.title }}</h2> <p>Author: {{ article.author.firstName }} {{ article.author.lastName }}</p> <p>{{ article.text }}</p> </article> {% endfor %}
  • 19. Symfony2 performance issues and improvements Beware of lazy loading Beware of lazy loading when querying entities with associations Apparent solution: {% for article in articles %} <article> <h2>{{ article.title }}</h2> <p>Author: {{ article.author.firstName }} {{ article.author.lastName }}</p> <p>{{ article.text }}</p> </article> {% endfor %} $articles = $this->getDoctrine()->getRepository('AcmeDemoBundle:Article')->findAll();
  • 20. Symfony2 performance issues and improvements Beware of lazy loading Right solution: // src/Acme/DemoBundle/Entity/Repository/ArticleRepository public function findAllWithAuthors() { $qb = $this->createQueryBuilder('article'); $qb->addSelect('author') ->innerJoin('article.author', 'author'); return $qb->getQuery()->getResult(); }
  • 21. Symfony2 performance issues and improvements Don't use hydration without needs Doctrine ORM, like most ORMs, is performing a process called Hydration when converting database results into objects. With hydration: Without hydration $articles = $this->createQueryBuilder('article')->getQuery()->getResult(); $articles = $this->createQueryBuilder('article')->getQuery()->getResult(Query::HYDRATE_ARRAY); $articles = $this->createQueryBuilder('article')->getQuery()->getArrayResult();
  • 22. Symfony2 performance issues and improvements Use Reference Proxies With get author query into DB: Without query for getting author: $author = $this->getDoctrine() ->getManagerForClass('AcmeDemoBundle:Article') ->getRepository('AcmeDemoBundle:Article')->find($authorId); $article = new Article(); $article->setAuthor($author); $em = $this->getDoctrine()->getManagerForClass('AcmeDemoBundle:Article'); $article = new Article(); $article->setAuthor($em->getReference('AcmeDemoBundle:Author', $authorId));
  • 23. Symfony2 performance issues and improvements Assets - Merging and minifying assets with Assetic (YUI compressor) - CSS at top javascript at bottom - use sprites for images - encode small images into base64 - run image optimizations on your images
  • 24. Symfony2 performance issues and improvements Use reverse proxy
  • 25. Symfony2 performance issues and improvements Bibliography ● http://blog.hma-info. de/content/stuff/Full_Stack_Web_Application_Performance_Tuning.pdf ● http://symfony.com/blog/push-it-to-the-limits-symfony2-for-high- performance-needs ● https://tideways.io/profiler/blog/5-ways-to-optimize-symfony-baseline- performance ● http://ocramius.github.io/blog/doctrine-orm-optimization-hydration ● http://labs.octivi.com/mastering-symfony2-performance-internals ● http://www.emanueleminotto.it/im-afraid-symfony-2-performances ● http://alexandre-salome.fr/media/sfpot-english.pdf
  • 26. Symfony2 performance issues and improvements Questions & Answers