SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
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

Contenu connexe

Dernier

How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераMark Opanasiuk
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandIES VE
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideStefan Dietze
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024Stephen Perrenod
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptxFIDO Alliance
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfFIDO Alliance
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...FIDO Alliance
 

Dernier (20)

How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider  Progress from Awareness to Implementation.pptxTales from a Passkey Provider  Progress from Awareness to Implementation.pptx
Tales from a Passkey Provider Progress from Awareness to Implementation.pptx
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 

En vedette

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
 

En vedette (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