SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Downloaden Sie, um offline zu lesen
Common Optimization
    Mistakes
  Dutch PHP Conference 2010

       Ilia Alshanetsky
         http://ilia.ws




                              1
Premature
               =
Optimization

Solve the business case,
 before optimizing the
        solution

                           2
Don’t Over Engineer

• Understand your audience
• Estimate the scale and growth of your
  application (based on facts, not
  marketing fiction)
• Keep timelines in mind when setting
  the project scope


                                          3
Simplify, Simplify &
      Simplify!
• Break complex tasks into simpler sub-
  components
• Don’t be afraid to modularize the code
• More code does not translate to slower
  code (common misconception)
  PHP has grown from less than 1 million LOC to over 2 million LOC
  since 2000 and has become at least 4 times faster.
  Linux kernel code base increase by 40% since 2005 and still
  managed to improve performance by roughly the same margin.
                                          LOC stats came from ohloh.net

                                                                          4
Hardware is Cheaper!


                  VS



  In most cases applications can gain vast
 performance gains by improving hardware,
quickly rather than through slow, error prone
          code optimization efforts.
                                                5
Hardware
• CPU bottlenecks can be resolved by
  more cores and/or CPUs. Typically
  each year yields a 20-30% speed
  improvement over past year’s CPU
  speeds.
• Ability to handle large amounts of
  traffic is often hampered by limited
  RAM, and thanks to 64bit, each new
  server can have tons of it.
                                        6
Hardware
• Drives are often the
  most common
  bottleneck,            SSD
  fortunately between
  RAID and Solid State
  you can solve that
  pretty easily now a
                         SCSI
  days.

                                7
Hardware Caveat
• While quick to give results, in some
  situations it will not help for long:
 • Database saturation
 • Non-scalable code base
 • Network bound bottleneck
 • Extremely low number sessions per
   server

                                          8
Optimize, but don’t
  touch the code
• Typically introduces substantial
  efficiencies
• Does not endanger code integrity
• Usually simple and quick to deploy
• In the event of problems, often simple
  to revert

                                           9
How PHP works in 30 seconds
            PHP Script                   • This cycle happens
                                           for every include
                                           file, not just for the
           Zend Compile                    "main" script.



           Zend Execute                    ire
                                    re   qu
                                  /
                           lude
                     in   c
                                         • Compilation can
                @
method                                     easily consume
function                                   more time than
  call                                     execution.
                                                                   10
Opcode Cache
• Each PHP script is interpreted only once for
  each revision.
• Reduced File IO, opcodes are being read from
  memory instead of being parsed from disk.
• Opcodes can optimized for faster execution.
• Yields a minimum 20-30% speed improvement
  and often as much as 200-400%


                                                 11
Quick Comparison
200
                                  Regular PHP
                                  Zend Platform
150
                                  APC
                                  X-Cache

100


 50


  0
 FUDforum   Smarty   phpMyAdmin

                                                  12
Use In-Memory Caches
• In-memory session storage is MUCH
  faster than disk or database equivalents.
 • Very simple via memcache extension
        session.save_handler = “memcache”
        session.save_path = “tcp://localhost:11211”


    Also allows scaling across multiple
    servers for improved reliability and
    performance.

                                                      13
Everything has to be
     Real-time




                       14
Complete Page Caching


 • Caching Proxy (Ex. Squid)
 • Page pre-generation
 • On-demand caching




                               15
Partial Cache - SQL
• In most applications the primary
  bottleneck can often be traced to
  “database work”.


• Caching of SQL can drastically reduce
  the load caused by unavoidable,
  complex queries.


                                          16
SQL Caching Example

$key = md5(“some sort of sql query”);
if (!($result = memcache_get($key))) {
  $result = $pdo->query($qry)->fetchAll();
  // cache query result for 1 hour
  memcache_set($key, $result, NULL, 3600);
}



                                             17
Partial Cache - Code
• Rather than optimizing complex PHP
  operations, it is often better to simply
  cache their output for a period of time.
 • Faster payoff
 • Lower chance of breaking the code
 • Faster then any “code optimization”


                                             18
Code Caching Example
function myFunction($a, $b, $c) {
  $key = __FUNCTION__ . serialize(func_get_args());
  if (!($result = memcache_get($key))) {
    $result = // function code
    // cache query result for 1 hour
    memcache_set($key, $result, NULL, 3600);
  }
  return $result;
}

                                                      19
Compile Your Tools

• Distribution binaries suck!


• More often than not you can realize
  10-15% speed increase by compiling
  your own Apache/PHP/Database from
  source. (unless you are using Gentoo)



                                          20
Output Buffering


• Don’t fear output buffering because it
  uses ram, ram is cheap. IO, not so
  much.




                                           21
Matching Your IO Sizes

  PHP          Apache           OS           Client



• The goal is to pass off as much work to the kernel
  as efficiently as possible.
• Optimizes PHP to OS Communication
• Reduces Number Of System Calls

                         22
                                                       22
PHP: Output Control

• Efficient
                           PHP         Apache
• Flexible
• In your script, with ob_start()
• Everywhere, with output_buffering = Xkb
• Improves browser’s rendering speed


                      23
                                                23
Apache: Output Control

• The idea is to hand off entire page to the
  kernel without blocking.

            Apache            OS

• Set SendBufferSize = PageSize




                                               24
OS: Output Control
OS (Linux)
                                 OS     Client

/proc/sys/net/ipv4/tcp_wmem
4096      16384      maxcontentsize
min        default         max


/proc/sys/net/ipv4/tcp_mem
(maxcontentsize * maxclients) / pagesize


✴   Be careful on low memory systems!
                                                 25
Upgrade Your PHP
• Before “upgrading” your code, upgrade
  your PHP. Newer versions are typically
  faster!
         150


        112.5
                                                 PHP 4.4
                                                 PHP 5.0
          75                                     PHP 5.1
                                                 PHP 5.2
         37.5                                    PHP 5.3
                                                 PHP-CSV

           0
                Speed % (base line of PHP 4.4)

                                                           26
Don’t Assume
Assume nothing,
profile everything!   • One of the most
                       common mistakes made
                       even by experienced
                       developers is starting to
                       optimize code without
                       identifying the
                       bottleneck first.


                                                   27
Profile, Profile & Profile


 Xdebug and XHProf extensions provide
 a very helpful mechanism for identifying
 TRUE bottlenecks in your code.




                                            28
Kcachegrind




Xdebug provides kcachegrind analyzable output that offers
  an easy visual overview of your performance problems
                                                            29
Database before code

• One of the most common mistakes
  people make is optimizing code before
  even looking at the database.


• Vast majority of applications have the
  bottleneck in the database not the code!


                                             30
Watch Your Errors

• Excessive, non-critical errors, such as
  E_NOTICE or E_STRICT can only be
  detected via error-logging.


• PHP code that generates any errors is
  going to impact performance!

    Not Easily Detectable by Profilers
                                            31
Micro Optimization

• Takes a long time
• Won’t solve your performance issues
• Almost guaranteed to break something
• Cost > Reward



                                         32
Speed vs Scale
• If you are planning for growth, scale is
  far more important than speed!



• Focus on scalability rather than speed,
  you can always increase scalable app,
  by simply adding more hardware.


                                             33
Don’t Re-invent the Wheel

          • Most attempts to
            make “faster”
            versions of native
            PHP functions using
            PHP code are silly
            exercises in futility.



                                     34
Write Only Code
• Removing comments won’t make code
  faster
• Neither will removal of whitespace
• Remember, you may need to debug that
  mess at some point ;-)
• Shorter code != Faster Code


                                         35
Thank You!
     Any Questions?



  Slides @ www.ilia.ws
Comments @ joind.in/1535

                           36

Weitere ähnliche Inhalte

Was ist angesagt?

PHP Performance with APC + Memcached
PHP Performance with APC + MemcachedPHP Performance with APC + Memcached
PHP Performance with APC + Memcached
Ford AntiTrust
 
Configuration manager presentation
Configuration manager presentationConfiguration manager presentation
Configuration manager presentation
jeyg
 

Was ist angesagt? (20)

Improving PHP Application Performance with APC
Improving PHP Application Performance with APCImproving PHP Application Performance with APC
Improving PHP Application Performance with APC
 
Caching with Memcached and APC
Caching with Memcached and APCCaching with Memcached and APC
Caching with Memcached and APC
 
Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i  Fundamentals of performance tuning PHP on IBM i
Fundamentals of performance tuning PHP on IBM i
 
Strategic Modernization with PHP on IBM i
Strategic Modernization with PHP on IBM iStrategic Modernization with PHP on IBM i
Strategic Modernization with PHP on IBM i
 
PHP Toolkit from Zend and IBM: Open Source on IBM i
PHP Toolkit from Zend and IBM: Open Source on IBM iPHP Toolkit from Zend and IBM: Open Source on IBM i
PHP Toolkit from Zend and IBM: Open Source on IBM i
 
PHP Performance with APC + Memcached
PHP Performance with APC + MemcachedPHP Performance with APC + Memcached
PHP Performance with APC + Memcached
 
Magento on HHVM. Daniel Sloof
Magento on HHVM. Daniel SloofMagento on HHVM. Daniel Sloof
Magento on HHVM. Daniel Sloof
 
/* pOrt80BKK */ - PHP Day - PHP Performance with APC + Memcached for Windows
/* pOrt80BKK */ - PHP Day - PHP Performance with APC + Memcached for Windows/* pOrt80BKK */ - PHP Day - PHP Performance with APC + Memcached for Windows
/* pOrt80BKK */ - PHP Day - PHP Performance with APC + Memcached for Windows
 
Create a welcoming development environment on IBM i
Create a welcoming development environment on IBM iCreate a welcoming development environment on IBM i
Create a welcoming development environment on IBM i
 
Apc presentation
Apc presentationApc presentation
Apc presentation
 
Zend Products and PHP for IBMi
Zend Products and PHP for IBMi  Zend Products and PHP for IBMi
Zend Products and PHP for IBMi
 
Getting started with PHP on IBM i
Getting started with PHP on IBM iGetting started with PHP on IBM i
Getting started with PHP on IBM i
 
Os Lamothe
Os LamotheOs Lamothe
Os Lamothe
 
PHP Batch Jobs on IBM i
PHP Batch Jobs on IBM iPHP Batch Jobs on IBM i
PHP Batch Jobs on IBM i
 
What's new with Zend server
What's new with Zend serverWhat's new with Zend server
What's new with Zend server
 
From Zero to ZF: Your first zend framework project on ibm i
From Zero to ZF: Your first zend framework project on ibm iFrom Zero to ZF: Your first zend framework project on ibm i
From Zero to ZF: Your first zend framework project on ibm i
 
PHP on IBM i Tutorial
PHP on IBM i TutorialPHP on IBM i Tutorial
PHP on IBM i Tutorial
 
Ndp Slides
Ndp SlidesNdp Slides
Ndp Slides
 
Configuration manager presentation
Configuration manager presentationConfiguration manager presentation
Configuration manager presentation
 
CakePHP 2.0 - PHP Matsuri 2011
CakePHP 2.0 - PHP Matsuri 2011CakePHP 2.0 - PHP Matsuri 2011
CakePHP 2.0 - PHP Matsuri 2011
 

Ähnlich wie Dutch php conference_2010_opm

Compilers and interpreters
Compilers and interpretersCompilers and interpreters
Compilers and interpreters
RAJU KATHI
 
Week 5
Week 5Week 5
Week 5
A VD
 
Week 5
Week 5Week 5
Week 5
A VD
 
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Atwix
 
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
Nexcess.net LLC
 

Ähnlich wie Dutch php conference_2010_opm (20)

Scaling with Symfony - PHP UK
Scaling with Symfony - PHP UKScaling with Symfony - PHP UK
Scaling with Symfony - PHP UK
 
Northeast PHP - High Performance PHP
Northeast PHP - High Performance PHPNortheast PHP - High Performance PHP
Northeast PHP - High Performance PHP
 
(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems(phpconftw2012) PHP as a Middleware in Embedded Systems
(phpconftw2012) PHP as a Middleware in Embedded Systems
 
Putting Compilers to Work
Putting Compilers to WorkPutting Compilers to Work
Putting Compilers to Work
 
Compilers and interpreters
Compilers and interpretersCompilers and interpreters
Compilers and interpreters
 
php & performance
 php & performance php & performance
php & performance
 
Ipc mysql php
Ipc mysql php Ipc mysql php
Ipc mysql php
 
Continuous Integration at Mollie
Continuous Integration at MollieContinuous Integration at Mollie
Continuous Integration at Mollie
 
PHP & Performance
PHP & PerformancePHP & Performance
PHP & Performance
 
EECI 2013 - ExpressionEngine Performance & Optimization - Laying a Solid Foun...
EECI 2013 - ExpressionEngine Performance & Optimization - Laying a Solid Foun...EECI 2013 - ExpressionEngine Performance & Optimization - Laying a Solid Foun...
EECI 2013 - ExpressionEngine Performance & Optimization - Laying a Solid Foun...
 
Week 5
Week 5Week 5
Week 5
 
Week 5
Week 5Week 5
Week 5
 
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
Host and Boast: Best Practices for Magento Hosting | Imagine 2013 Technolog…
 
High performance PHP: Scaling and getting the most out of your infrastructure
High performance PHP: Scaling and getting the most out of your infrastructureHigh performance PHP: Scaling and getting the most out of your infrastructure
High performance PHP: Scaling and getting the most out of your infrastructure
 
Zendcon scaling magento
Zendcon scaling magentoZendcon scaling magento
Zendcon scaling magento
 
Ria Applications And PHP
Ria Applications And PHPRia Applications And PHP
Ria Applications And PHP
 
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
ExpressionEngine - Simple Steps to Performance and Security (EECI 2014)
 
Lamp Introduction 20100419
Lamp Introduction 20100419Lamp Introduction 20100419
Lamp Introduction 20100419
 
Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?Comment améliorer le quotidien des Développeurs PHP ?
Comment améliorer le quotidien des Développeurs PHP ?
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast Websites
 

Mehr von isnull

站点报告模板
站点报告模板站点报告模板
站点报告模板
isnull
 
My sql数据库开发的三十六条军规
My sql数据库开发的三十六条军规My sql数据库开发的三十六条军规
My sql数据库开发的三十六条军规
isnull
 
基于Web的项目管理工具redmine
基于Web的项目管理工具redmine基于Web的项目管理工具redmine
基于Web的项目管理工具redmine
isnull
 
雷志兴 百度前端基础平台与架构分享
雷志兴 百度前端基础平台与架构分享雷志兴 百度前端基础平台与架构分享
雷志兴 百度前端基础平台与架构分享
isnull
 
张勇 搜搜前端架构
张勇 搜搜前端架构张勇 搜搜前端架构
张勇 搜搜前端架构
isnull
 
张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式
isnull
 
杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享
isnull
 
Barcelona apc mem2010
Barcelona apc mem2010Barcelona apc mem2010
Barcelona apc mem2010
isnull
 
Mysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimizationMysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimization
isnull
 
Designofhtml5
Designofhtml5Designofhtml5
Designofhtml5
isnull
 
Mysql开发与优化
Mysql开发与优化Mysql开发与优化
Mysql开发与优化
isnull
 
我的Ubuntu之旅
我的Ubuntu之旅我的Ubuntu之旅
我的Ubuntu之旅
isnull
 
软件工程&架构
软件工程&架构软件工程&架构
软件工程&架构
isnull
 
淘宝分布式数据处理实践
淘宝分布式数据处理实践淘宝分布式数据处理实践
淘宝分布式数据处理实践
isnull
 
阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训
isnull
 
183银行服务器下载说明
183银行服务器下载说明183银行服务器下载说明
183银行服务器下载说明
isnull
 
人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析
isnull
 
Data on the web
Data on the webData on the web
Data on the web
isnull
 

Mehr von isnull (20)

站点报告模板
站点报告模板站点报告模板
站点报告模板
 
My sql数据库开发的三十六条军规
My sql数据库开发的三十六条军规My sql数据库开发的三十六条军规
My sql数据库开发的三十六条军规
 
基于Web的项目管理工具redmine
基于Web的项目管理工具redmine基于Web的项目管理工具redmine
基于Web的项目管理工具redmine
 
雷志兴 百度前端基础平台与架构分享
雷志兴 百度前端基础平台与架构分享雷志兴 百度前端基础平台与架构分享
雷志兴 百度前端基础平台与架构分享
 
张勇 搜搜前端架构
张勇 搜搜前端架构张勇 搜搜前端架构
张勇 搜搜前端架构
 
张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式张克军 豆瓣前端团队的工作方式
张克军 豆瓣前端团队的工作方式
 
杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享杨皓 新浪博客前端架构分享
杨皓 新浪博客前端架构分享
 
Barcelona apc mem2010
Barcelona apc mem2010Barcelona apc mem2010
Barcelona apc mem2010
 
Mysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimizationMysql introduction-and-performance-optimization
Mysql introduction-and-performance-optimization
 
Designofhtml5
Designofhtml5Designofhtml5
Designofhtml5
 
Mysql开发与优化
Mysql开发与优化Mysql开发与优化
Mysql开发与优化
 
我的Ubuntu之旅
我的Ubuntu之旅我的Ubuntu之旅
我的Ubuntu之旅
 
软件工程&架构
软件工程&架构软件工程&架构
软件工程&架构
 
淘宝分布式数据处理实践
淘宝分布式数据处理实践淘宝分布式数据处理实践
淘宝分布式数据处理实践
 
阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训阿里巴巴 招聘技巧培训
阿里巴巴 招聘技巧培训
 
Scrum
ScrumScrum
Scrum
 
Scrum
ScrumScrum
Scrum
 
183银行服务器下载说明
183银行服务器下载说明183银行服务器下载说明
183银行服务器下载说明
 
人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析人人网技术经理张铁安 Feed系统结构浅析
人人网技术经理张铁安 Feed系统结构浅析
 
Data on the web
Data on the webData on the web
Data on the web
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Dutch php conference_2010_opm

  • 1. Common Optimization Mistakes Dutch PHP Conference 2010 Ilia Alshanetsky http://ilia.ws 1
  • 2. Premature = Optimization Solve the business case, before optimizing the solution 2
  • 3. Don’t Over Engineer • Understand your audience • Estimate the scale and growth of your application (based on facts, not marketing fiction) • Keep timelines in mind when setting the project scope 3
  • 4. Simplify, Simplify & Simplify! • Break complex tasks into simpler sub- components • Don’t be afraid to modularize the code • More code does not translate to slower code (common misconception) PHP has grown from less than 1 million LOC to over 2 million LOC since 2000 and has become at least 4 times faster. Linux kernel code base increase by 40% since 2005 and still managed to improve performance by roughly the same margin. LOC stats came from ohloh.net 4
  • 5. Hardware is Cheaper! VS In most cases applications can gain vast performance gains by improving hardware, quickly rather than through slow, error prone code optimization efforts. 5
  • 6. Hardware • CPU bottlenecks can be resolved by more cores and/or CPUs. Typically each year yields a 20-30% speed improvement over past year’s CPU speeds. • Ability to handle large amounts of traffic is often hampered by limited RAM, and thanks to 64bit, each new server can have tons of it. 6
  • 7. Hardware • Drives are often the most common bottleneck, SSD fortunately between RAID and Solid State you can solve that pretty easily now a SCSI days. 7
  • 8. Hardware Caveat • While quick to give results, in some situations it will not help for long: • Database saturation • Non-scalable code base • Network bound bottleneck • Extremely low number sessions per server 8
  • 9. Optimize, but don’t touch the code • Typically introduces substantial efficiencies • Does not endanger code integrity • Usually simple and quick to deploy • In the event of problems, often simple to revert 9
  • 10. How PHP works in 30 seconds PHP Script • This cycle happens for every include file, not just for the Zend Compile "main" script. Zend Execute ire re qu / lude in c • Compilation can @ method easily consume function more time than call execution. 10
  • 11. Opcode Cache • Each PHP script is interpreted only once for each revision. • Reduced File IO, opcodes are being read from memory instead of being parsed from disk. • Opcodes can optimized for faster execution. • Yields a minimum 20-30% speed improvement and often as much as 200-400% 11
  • 12. Quick Comparison 200 Regular PHP Zend Platform 150 APC X-Cache 100 50 0 FUDforum Smarty phpMyAdmin 12
  • 13. Use In-Memory Caches • In-memory session storage is MUCH faster than disk or database equivalents. • Very simple via memcache extension session.save_handler = “memcache” session.save_path = “tcp://localhost:11211” Also allows scaling across multiple servers for improved reliability and performance. 13
  • 14. Everything has to be Real-time 14
  • 15. Complete Page Caching • Caching Proxy (Ex. Squid) • Page pre-generation • On-demand caching 15
  • 16. Partial Cache - SQL • In most applications the primary bottleneck can often be traced to “database work”. • Caching of SQL can drastically reduce the load caused by unavoidable, complex queries. 16
  • 17. SQL Caching Example $key = md5(“some sort of sql query”); if (!($result = memcache_get($key))) { $result = $pdo->query($qry)->fetchAll(); // cache query result for 1 hour memcache_set($key, $result, NULL, 3600); } 17
  • 18. Partial Cache - Code • Rather than optimizing complex PHP operations, it is often better to simply cache their output for a period of time. • Faster payoff • Lower chance of breaking the code • Faster then any “code optimization” 18
  • 19. Code Caching Example function myFunction($a, $b, $c) { $key = __FUNCTION__ . serialize(func_get_args()); if (!($result = memcache_get($key))) { $result = // function code // cache query result for 1 hour memcache_set($key, $result, NULL, 3600); } return $result; } 19
  • 20. Compile Your Tools • Distribution binaries suck! • More often than not you can realize 10-15% speed increase by compiling your own Apache/PHP/Database from source. (unless you are using Gentoo) 20
  • 21. Output Buffering • Don’t fear output buffering because it uses ram, ram is cheap. IO, not so much. 21
  • 22. Matching Your IO Sizes PHP Apache OS Client • The goal is to pass off as much work to the kernel as efficiently as possible. • Optimizes PHP to OS Communication • Reduces Number Of System Calls 22 22
  • 23. PHP: Output Control • Efficient PHP Apache • Flexible • In your script, with ob_start() • Everywhere, with output_buffering = Xkb • Improves browser’s rendering speed 23 23
  • 24. Apache: Output Control • The idea is to hand off entire page to the kernel without blocking. Apache OS • Set SendBufferSize = PageSize 24
  • 25. OS: Output Control OS (Linux) OS Client /proc/sys/net/ipv4/tcp_wmem 4096 16384 maxcontentsize min default max /proc/sys/net/ipv4/tcp_mem (maxcontentsize * maxclients) / pagesize ✴ Be careful on low memory systems! 25
  • 26. Upgrade Your PHP • Before “upgrading” your code, upgrade your PHP. Newer versions are typically faster! 150 112.5 PHP 4.4 PHP 5.0 75 PHP 5.1 PHP 5.2 37.5 PHP 5.3 PHP-CSV 0 Speed % (base line of PHP 4.4) 26
  • 27. Don’t Assume Assume nothing, profile everything! • One of the most common mistakes made even by experienced developers is starting to optimize code without identifying the bottleneck first. 27
  • 28. Profile, Profile & Profile Xdebug and XHProf extensions provide a very helpful mechanism for identifying TRUE bottlenecks in your code. 28
  • 29. Kcachegrind Xdebug provides kcachegrind analyzable output that offers an easy visual overview of your performance problems 29
  • 30. Database before code • One of the most common mistakes people make is optimizing code before even looking at the database. • Vast majority of applications have the bottleneck in the database not the code! 30
  • 31. Watch Your Errors • Excessive, non-critical errors, such as E_NOTICE or E_STRICT can only be detected via error-logging. • PHP code that generates any errors is going to impact performance! Not Easily Detectable by Profilers 31
  • 32. Micro Optimization • Takes a long time • Won’t solve your performance issues • Almost guaranteed to break something • Cost > Reward 32
  • 33. Speed vs Scale • If you are planning for growth, scale is far more important than speed! • Focus on scalability rather than speed, you can always increase scalable app, by simply adding more hardware. 33
  • 34. Don’t Re-invent the Wheel • Most attempts to make “faster” versions of native PHP functions using PHP code are silly exercises in futility. 34
  • 35. Write Only Code • Removing comments won’t make code faster • Neither will removal of whitespace • Remember, you may need to debug that mess at some point ;-) • Shorter code != Faster Code 35
  • 36. Thank You! Any Questions? Slides @ www.ilia.ws Comments @ joind.in/1535 36