SlideShare a Scribd company logo
PHP Optimization
by Dave Jesch - SpectrOMTech.com
OC WordCamp - June 7, 2014
How to make your code run faster
There will be code.
Warning:
© 2014 SpectrOMTech.com. All Rights Reserved.
Optimization
Dave Jesch, Lifetime Geek
➔1.0 Web Applications
➔Sales Conversion Plugins
➔eCommerce Solutions
Principal, SpectrOMTech.com
© 2014 SpectrOMTech.com. All Rights Reserved.
Mastering Security & Optimization...
© 2014 SpectrOMTech.com. All Rights Reserved.
1. How to Measure Improvement
2. Basic Optimization Techniques
3. Code Examples
Today’s Goals:
© 2014 SpectrOMTech.com. All Rights Reserved.
Secret Behind Optimization
© 2014 SpectrOMTech.com. All Rights Reserved.
1. Ways to Measure Outcome
© 2014 SpectrOMTech.com. All Rights Reserved.
What are we Measuring?
● Speed
● Memory
● Code simplification / maintenance
© 2014 SpectrOMTech.com. All Rights Reserved.
Number of Operations
O(n) notation is used to express the worst case
order of growth of an algorithm.
How an algorithm’s worst-case performance changes as
the size of the data set it operates on increases.
http://www.perlmonks.org/?node_id=227909
© 2014 SpectrOMTech.com. All Rights Reserved.
microtime()
http://us1.php.net/manual/en/function.microtime.php
memory_get_usage()
http://us1.php.net/manual/en/function.memory-get-usage.php
XDebug Profiler
http://www.xdebug.org/docs/profiler
Measuring Tools
© 2014 SpectrOMTech.com. All Rights Reserved.
2. Let’s make your code Awesome!
© 2014 SpectrOMTech.com. All Rights Reserved.
General Optimizations (1 of 7)
● Upgrade!
● 'string' is not the same as "string".
[2.62 : 3.78 @10,000,000]
● Use built-in functions, especially for arrays and strings.
array_column()/array_replace()/implode()/
explode(), etc.
© 2014 SpectrOMTech.com. All Rights Reserved.
General Optimizations (2 of 7)
● Identity 1===1 vs. Equality '1' == 1
[1.63 : 3.72 @10,000,000]
● Shift (n >> 1), not divide (n / 2)
[2.34 : 2.75 @10,000,000]
● Don’t make needless copies.
© 2014 SpectrOMTech.com. All Rights Reserved.
General Optimizations (3 of 7)
● Use reference operator $x = &$array['key']
[1.95 : 2.01 @10,000,000]
● unset large arrays when no longer needed.
● echo $a,$b; faster than echo $a.$b;
[1.11 : 2.48 @1,000,000]
© 2014 SpectrOMTech.com. All Rights Reserved.
General Optimizations (4 of 7)
● Avoid @ error control operator.
● Pre increment ++$i faster than post increment $i++
[0.95 : 1.05 @10,000,000]
● "foreach" for arrays is better than "for"
[1.38 : 4.35 @100,000]
© 2014 SpectrOMTech.com. All Rights Reserved.
General Optimizations (5 of 7)
● Initialize! using undefined variables is slower than pre-
initialized variables.
[0.82 : 4.41 @10,000,000]
● Don’t global unless you use it.
[1.82 : 2.01 @10,000,000]
● switch is faster than if (…) elseif (…) ...
© 2014 SpectrOMTech.com. All Rights Reserved.
General Optimizations (6 of 7)
● !isset($foo{5}) faster than strlen($foo) < 5
[0.26 : 0.84 @10,000,000]
● str_replace() faster than preg_replace()
strtr() faster than str_replace()
[0.47 : 0.49 : 1.05 @100,000]
© 2014 SpectrOMTech.com. All Rights Reserved.
General Optimizations (7 of 7)
● "{$var}" is faster than sprintf()
[2.19 : 6.87 @10,000,000]
● incrementing global var slightly slower than a local var
[8.98 : 9.09 @100,000,000]
● use ctype_alnum(), ctype_alpha() and
ctype_digit() over regex
© 2014 SpectrOMTech.com. All Rights Reserved.
3. Examples:
© 2014 SpectrOMTech.com. All Rights Reserved.
Bubble Sort
Optimized: O(n^2) Best case: O(n)
$len = count($arr);
for ($i = 0; $i < $len; ++$i) {
$swapped = false;
for ($j = 0; $j < $len - 1; ++$j) {
if ($arr[$i] < $arr[$j]) {
$x = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $x;
$swapped = true;
}
}
if (!$swapped)
break;
}
Non-Optimized: O(n^2)
for ($i = 0; $i < count($arr); $i++) {
for ($j = 0; $j < count($arr) - 1; $j++) {
if ($arr[$i] < $arr[$j]) {
$x = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $x;
}
}
}
© 2014 SpectrOMTech.com. All Rights Reserved.
Reuse Function Results
Non-Optimized:
if (get_option('some_setting') > 0)
$var = get_option('some_setting');
else
$var = 0;
Optimized:
// use option or set to 0 if option not set
if (($var = get_option('some_setting')) < 0)
$var = 0;
© 2014 SpectrOMTech.com. All Rights Reserved.
Iterating Arrays
Non-Optimized:
// iterate through an array
foreach ($aHash as $key => $val) {
call_func($aHash[$key]);
}
12.01 seconds @10,000,000
Optimized:
// iterate through an array
while (list($key) = each($aHash)) {
call_func($aHash[$key]);
}
0.73 seconds @10,000,000
© 2014 SpectrOMTech.com. All Rights Reserved.
For Loops
Non-Optimized:
// loop through all elements of array
for ($i = 0; $i < count($a); ++$i) {
// do something
}
Optimized:
// loop through all elements of array
for ($i = 0, $c = count($a); $i < $c; ++$i) {
// do something
}
© 2014 SpectrOMTech.com. All Rights Reserved.
Latency Solutions: Transients
// get data from transient
if (($value = get_transient('my_transient_name')) === false) {
// nothing in transient, get from remote API
$value = wp_remote_get('http://some-domain.com', $args);
// save data from API in transient
set_transient('my_transient_name', $value, $expiration);
}
© 2014 SpectrOMTech.com. All Rights Reserved.
Ordering of Conditions
if (fastest() || fast() || slowest()) {
// some code here
}
________________________________________________________________
if (op1() && op2() && op3()) {
// more code
}
© 2014 SpectrOMTech.com. All Rights Reserved.
Code Optimized!
1. Practice, practice, practice
2. Always more to learn
3. Balancing act
4. Art form meets science
© 2014 SpectrOMTech.com. All Rights Reserved.
WP Geek Lab- Give back to WordPress.org
Alone we can do so little; together we can do so much. - Helen Keller
Connect with us at Hello@SpectrOMTech.com for more info.
write code...fix bugs...hangout...talk geek...
More References
http://phplens.com/lens/php-book/optimizing-debugging-php.php
http://alexatnet.com/articles/php-micro-optimization-tips
http://www.mdproductions.ca/guides/50-best-practices-to-optimize-php-code-
performance
http://php100.wordpress.com/2009/06/26/php-performance-google/
© 2014 SpectrOMTech.com. All Rights Reserved.

More Related Content

What's hot

Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)
julien pauli
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objectsjulien pauli
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
Laurent Dami
 
PHP 7 new engine
PHP 7 new enginePHP 7 new engine
PHP 7 new engine
julien pauli
 
When e-commerce meets Symfony
When e-commerce meets SymfonyWhen e-commerce meets Symfony
When e-commerce meets Symfony
Marc Morera
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0
Tim Bunce
 
Php and threads ZTS
Php and threads ZTSPhp and threads ZTS
Php and threads ZTS
julien pauli
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
julien pauli
 
Kansai.pm 10周年記念 Plack/PSGI 入門
Kansai.pm 10周年記念 Plack/PSGI 入門Kansai.pm 10周年記念 Plack/PSGI 入門
Kansai.pm 10周年記念 Plack/PSGI 入門lestrrat
 
Understanding PHP memory
Understanding PHP memoryUnderstanding PHP memory
Understanding PHP memoryjulien pauli
 
PL/Perl - New Features in PostgreSQL 9.0 201012
PL/Perl - New Features in PostgreSQL 9.0 201012PL/Perl - New Features in PostgreSQL 9.0 201012
PL/Perl - New Features in PostgreSQL 9.0 201012
Tim Bunce
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
julien pauli
 
The Php Life Cycle
The Php Life CycleThe Php Life Cycle
The Php Life CycleXinchen Hui
 
PHP Tips for certification - OdW13
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13julien pauli
 
Php 7 hhvm and co
Php 7 hhvm and coPhp 7 hhvm and co
Php 7 hhvm and co
Pierre Joye
 
PHP5.5 is Here
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
julien pauli
 
PHP 7 OPCache extension review
PHP 7 OPCache extension reviewPHP 7 OPCache extension review
PHP 7 OPCache extension review
julien pauli
 
PHP
PHPPHP
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
Wim Godden
 

What's hot (20)

Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)Php in 2013 (Web-5 2013 conference)
Php in 2013 (Web-5 2013 conference)
 
Understanding PHP objects
Understanding PHP objectsUnderstanding PHP objects
Understanding PHP objects
 
Working with databases in Perl
Working with databases in PerlWorking with databases in Perl
Working with databases in Perl
 
PHP 7 new engine
PHP 7 new enginePHP 7 new engine
PHP 7 new engine
 
When e-commerce meets Symfony
When e-commerce meets SymfonyWhen e-commerce meets Symfony
When e-commerce meets Symfony
 
PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0PL/Perl - New Features in PostgreSQL 9.0
PL/Perl - New Features in PostgreSQL 9.0
 
Building Custom PHP Extensions
Building Custom PHP ExtensionsBuilding Custom PHP Extensions
Building Custom PHP Extensions
 
Php and threads ZTS
Php and threads ZTSPhp and threads ZTS
Php and threads ZTS
 
Quick tour of PHP from inside
Quick tour of PHP from insideQuick tour of PHP from inside
Quick tour of PHP from inside
 
Kansai.pm 10周年記念 Plack/PSGI 入門
Kansai.pm 10周年記念 Plack/PSGI 入門Kansai.pm 10周年記念 Plack/PSGI 入門
Kansai.pm 10周年記念 Plack/PSGI 入門
 
Understanding PHP memory
Understanding PHP memoryUnderstanding PHP memory
Understanding PHP memory
 
PL/Perl - New Features in PostgreSQL 9.0 201012
PL/Perl - New Features in PostgreSQL 9.0 201012PL/Perl - New Features in PostgreSQL 9.0 201012
PL/Perl - New Features in PostgreSQL 9.0 201012
 
PHP7 is coming
PHP7 is comingPHP7 is coming
PHP7 is coming
 
The Php Life Cycle
The Php Life CycleThe Php Life Cycle
The Php Life Cycle
 
PHP Tips for certification - OdW13
PHP Tips for certification - OdW13PHP Tips for certification - OdW13
PHP Tips for certification - OdW13
 
Php 7 hhvm and co
Php 7 hhvm and coPhp 7 hhvm and co
Php 7 hhvm and co
 
PHP5.5 is Here
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
 
PHP 7 OPCache extension review
PHP 7 OPCache extension reviewPHP 7 OPCache extension review
PHP 7 OPCache extension review
 
PHP
PHPPHP
PHP
 
Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011Caching and tuning fun for high scalability @ FrOSCon 2011
Caching and tuning fun for high scalability @ FrOSCon 2011
 

Viewers also liked

Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
Elizabeth Smith
 
PHP WTF
PHP WTFPHP WTF
PHP WTF
markstory
 
Php
PhpPhp
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)
David de Boer
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
Anthony Ferrara
 
Internet of Things With PHP
Internet of Things With PHPInternet of Things With PHP
Internet of Things With PHP
Adam Englander
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
Vikas Chauhan
 
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
Shengyou Fan
 
How PHP Works ?
How PHP Works ?How PHP Works ?
How PHP Works ?
Ravi Raj
 
LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕
Shengyou Fan
 
Route 路由控制
Route 路由控制Route 路由控制
Route 路由控制
Shengyou Fan
 

Viewers also liked (12)

Php internal architecture
Php internal architecturePhp internal architecture
Php internal architecture
 
PHP WTF
PHP WTFPHP WTF
PHP WTF
 
Php
PhpPhp
Php
 
Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)Being functional in PHP (PHPDay Italy 2016)
Being functional in PHP (PHPDay Italy 2016)
 
PHP, Under The Hood - DPC
PHP, Under The Hood - DPCPHP, Under The Hood - DPC
PHP, Under The Hood - DPC
 
Internet of Things With PHP
Internet of Things With PHPInternet of Things With PHP
Internet of Things With PHP
 
Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1Laravel Beginners Tutorial 1
Laravel Beginners Tutorial 1
 
Php 101: PDO
Php 101: PDOPhp 101: PDO
Php 101: PDO
 
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南[Community Open Camp] 給 PHP 開發者的 VS Code 指南
[Community Open Camp] 給 PHP 開發者的 VS Code 指南
 
How PHP Works ?
How PHP Works ?How PHP Works ?
How PHP Works ?
 
LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕LaravelConf Taiwan 2017 開幕
LaravelConf Taiwan 2017 開幕
 
Route 路由控制
Route 路由控制Route 路由控制
Route 路由控制
 

Similar to PHP Optimization

Ten Battle-Tested Tips for Atlassian Connect Add-ons
Ten Battle-Tested Tips for Atlassian Connect Add-onsTen Battle-Tested Tips for Atlassian Connect Add-ons
Ten Battle-Tested Tips for Atlassian Connect Add-ons
Atlassian
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
Venkata Ramana
 
Regular Expressions with full Unicode support
Regular Expressions with full Unicode supportRegular Expressions with full Unicode support
Regular Expressions with full Unicode support
MartinHanssonOracle
 
MySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance SchemaMySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance Schema
Sveta Smirnova
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
Peter Gfader
 
WordCamp LA 2014- Writing Code that Scales
WordCamp LA 2014-  Writing Code that ScalesWordCamp LA 2014-  Writing Code that Scales
WordCamp LA 2014- Writing Code that Scales
SpectrOMTech.com
 
MySQL-Performance Schema- What's new in MySQL-5.7 DMRs
MySQL-Performance Schema- What's new in MySQL-5.7 DMRsMySQL-Performance Schema- What's new in MySQL-5.7 DMRs
MySQL-Performance Schema- What's new in MySQL-5.7 DMRs
Mayank Prasad
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
Haim Michael
 
Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...
Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...
Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...
Amazon Web Services
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
SWIFTotter Solutions
 
Benchmarking and PHPBench
Benchmarking and PHPBenchBenchmarking and PHPBench
Benchmarking and PHPBench
dantleech
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
Mike Lively
 
HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...
HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...
HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...
Yuji Kubota
 
A3 sec -_regular_expressions
A3 sec -_regular_expressionsA3 sec -_regular_expressions
A3 sec -_regular_expressionsa3sec
 
Cより速いRubyプログラム
Cより速いRubyプログラムCより速いRubyプログラム
Cより速いRubyプログラム
kwatch
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
markstory
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 

Similar to PHP Optimization (20)

Ten Battle-Tested Tips for Atlassian Connect Add-ons
Ten Battle-Tested Tips for Atlassian Connect Add-onsTen Battle-Tested Tips for Atlassian Connect Add-ons
Ten Battle-Tested Tips for Atlassian Connect Add-ons
 
2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps2010 07-28-testing-zf-apps
2010 07-28-testing-zf-apps
 
Regular Expressions with full Unicode support
Regular Expressions with full Unicode supportRegular Expressions with full Unicode support
Regular Expressions with full Unicode support
 
MySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance SchemaMySQL Troubleshooting with the Performance Schema
MySQL Troubleshooting with the Performance Schema
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
WordCamp LA 2014- Writing Code that Scales
WordCamp LA 2014-  Writing Code that ScalesWordCamp LA 2014-  Writing Code that Scales
WordCamp LA 2014- Writing Code that Scales
 
MySQL-Performance Schema- What's new in MySQL-5.7 DMRs
MySQL-Performance Schema- What's new in MySQL-5.7 DMRsMySQL-Performance Schema- What's new in MySQL-5.7 DMRs
MySQL-Performance Schema- What's new in MySQL-5.7 DMRs
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
PHP7. Game Changer.
PHP7. Game Changer. PHP7. Game Changer.
PHP7. Game Changer.
 
Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...
Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...
Uber on Using Horovod for Distributed Deep Learning (AIM411) - AWS re:Invent ...
 
What's new with PHP7
What's new with PHP7What's new with PHP7
What's new with PHP7
 
Benchmarking and PHPBench
Benchmarking and PHPBenchBenchmarking and PHPBench
Benchmarking and PHPBench
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...
HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...
HeapStats: Troubleshooting with Serviceability and the New Runtime Monitoring...
 
A3 sec -_regular_expressions
A3 sec -_regular_expressionsA3 sec -_regular_expressions
A3 sec -_regular_expressions
 
Cより速いRubyプログラム
Cより速いRubyプログラムCより速いRubyプログラム
Cより速いRubyプログラム
 
PHPunit and you
PHPunit and youPHPunit and you
PHPunit and you
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 

Recently uploaded

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
Adele Miller
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
Alina Yurenko
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
Aftab Hussain
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Łukasz Chruściel
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Crescat
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Neo4j
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
vrstrong314
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
abdulrafaychaudhry
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
ShamsuddeenMuhammadA
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 

Recently uploaded (20)

Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
May Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdfMay Marketo Masterclass, London MUG May 22 2024.pdf
May Marketo Masterclass, London MUG May 22 2024.pdf
 
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)GOING AOT WITH GRAALVM FOR  SPRING BOOT (SPRING IO)
GOING AOT WITH GRAALVM FOR SPRING BOOT (SPRING IO)
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024OpenMetadata Community Meeting - 5th June 2024
OpenMetadata Community Meeting - 5th June 2024
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeA Study of Variable-Role-based Feature Enrichment in Neural Models of Code
A Study of Variable-Role-based Feature Enrichment in Neural Models of Code
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️Need for Speed: Removing speed bumps from your Symfony projects ⚡️
Need for Speed: Removing speed bumps from your Symfony projects ⚡️
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...
 
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissancesAtelier - Innover avec l’IA Générative et les graphes de connaissances
Atelier - Innover avec l’IA Générative et les graphes de connaissances
 
Nidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, TipsNidhi Software Price. Fact , Costs, Tips
Nidhi Software Price. Fact , Costs, Tips
 
Game Development with Unity3D (Game Development lecture 3)
Game Development  with Unity3D (Game Development lecture 3)Game Development  with Unity3D (Game Development lecture 3)
Game Development with Unity3D (Game Development lecture 3)
 
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptxText-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
Text-Summarization-of-Breaking-News-Using-Fine-tuning-BART-Model.pptx
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 

PHP Optimization

  • 1. PHP Optimization by Dave Jesch - SpectrOMTech.com OC WordCamp - June 7, 2014 How to make your code run faster
  • 2. There will be code. Warning: © 2014 SpectrOMTech.com. All Rights Reserved.
  • 3. Optimization Dave Jesch, Lifetime Geek ➔1.0 Web Applications ➔Sales Conversion Plugins ➔eCommerce Solutions Principal, SpectrOMTech.com © 2014 SpectrOMTech.com. All Rights Reserved.
  • 4. Mastering Security & Optimization... © 2014 SpectrOMTech.com. All Rights Reserved.
  • 5. 1. How to Measure Improvement 2. Basic Optimization Techniques 3. Code Examples Today’s Goals: © 2014 SpectrOMTech.com. All Rights Reserved.
  • 6. Secret Behind Optimization © 2014 SpectrOMTech.com. All Rights Reserved.
  • 7. 1. Ways to Measure Outcome © 2014 SpectrOMTech.com. All Rights Reserved.
  • 8. What are we Measuring? ● Speed ● Memory ● Code simplification / maintenance © 2014 SpectrOMTech.com. All Rights Reserved.
  • 9. Number of Operations O(n) notation is used to express the worst case order of growth of an algorithm. How an algorithm’s worst-case performance changes as the size of the data set it operates on increases. http://www.perlmonks.org/?node_id=227909 © 2014 SpectrOMTech.com. All Rights Reserved.
  • 11. 2. Let’s make your code Awesome! © 2014 SpectrOMTech.com. All Rights Reserved.
  • 12. General Optimizations (1 of 7) ● Upgrade! ● 'string' is not the same as "string". [2.62 : 3.78 @10,000,000] ● Use built-in functions, especially for arrays and strings. array_column()/array_replace()/implode()/ explode(), etc. © 2014 SpectrOMTech.com. All Rights Reserved.
  • 13. General Optimizations (2 of 7) ● Identity 1===1 vs. Equality '1' == 1 [1.63 : 3.72 @10,000,000] ● Shift (n >> 1), not divide (n / 2) [2.34 : 2.75 @10,000,000] ● Don’t make needless copies. © 2014 SpectrOMTech.com. All Rights Reserved.
  • 14. General Optimizations (3 of 7) ● Use reference operator $x = &$array['key'] [1.95 : 2.01 @10,000,000] ● unset large arrays when no longer needed. ● echo $a,$b; faster than echo $a.$b; [1.11 : 2.48 @1,000,000] © 2014 SpectrOMTech.com. All Rights Reserved.
  • 15. General Optimizations (4 of 7) ● Avoid @ error control operator. ● Pre increment ++$i faster than post increment $i++ [0.95 : 1.05 @10,000,000] ● "foreach" for arrays is better than "for" [1.38 : 4.35 @100,000] © 2014 SpectrOMTech.com. All Rights Reserved.
  • 16. General Optimizations (5 of 7) ● Initialize! using undefined variables is slower than pre- initialized variables. [0.82 : 4.41 @10,000,000] ● Don’t global unless you use it. [1.82 : 2.01 @10,000,000] ● switch is faster than if (…) elseif (…) ... © 2014 SpectrOMTech.com. All Rights Reserved.
  • 17. General Optimizations (6 of 7) ● !isset($foo{5}) faster than strlen($foo) < 5 [0.26 : 0.84 @10,000,000] ● str_replace() faster than preg_replace() strtr() faster than str_replace() [0.47 : 0.49 : 1.05 @100,000] © 2014 SpectrOMTech.com. All Rights Reserved.
  • 18. General Optimizations (7 of 7) ● "{$var}" is faster than sprintf() [2.19 : 6.87 @10,000,000] ● incrementing global var slightly slower than a local var [8.98 : 9.09 @100,000,000] ● use ctype_alnum(), ctype_alpha() and ctype_digit() over regex © 2014 SpectrOMTech.com. All Rights Reserved.
  • 19. 3. Examples: © 2014 SpectrOMTech.com. All Rights Reserved.
  • 20. Bubble Sort Optimized: O(n^2) Best case: O(n) $len = count($arr); for ($i = 0; $i < $len; ++$i) { $swapped = false; for ($j = 0; $j < $len - 1; ++$j) { if ($arr[$i] < $arr[$j]) { $x = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $x; $swapped = true; } } if (!$swapped) break; } Non-Optimized: O(n^2) for ($i = 0; $i < count($arr); $i++) { for ($j = 0; $j < count($arr) - 1; $j++) { if ($arr[$i] < $arr[$j]) { $x = $arr[$i]; $arr[$i] = $arr[$j]; $arr[$j] = $x; } } } © 2014 SpectrOMTech.com. All Rights Reserved.
  • 21. Reuse Function Results Non-Optimized: if (get_option('some_setting') > 0) $var = get_option('some_setting'); else $var = 0; Optimized: // use option or set to 0 if option not set if (($var = get_option('some_setting')) < 0) $var = 0; © 2014 SpectrOMTech.com. All Rights Reserved.
  • 22. Iterating Arrays Non-Optimized: // iterate through an array foreach ($aHash as $key => $val) { call_func($aHash[$key]); } 12.01 seconds @10,000,000 Optimized: // iterate through an array while (list($key) = each($aHash)) { call_func($aHash[$key]); } 0.73 seconds @10,000,000 © 2014 SpectrOMTech.com. All Rights Reserved.
  • 23. For Loops Non-Optimized: // loop through all elements of array for ($i = 0; $i < count($a); ++$i) { // do something } Optimized: // loop through all elements of array for ($i = 0, $c = count($a); $i < $c; ++$i) { // do something } © 2014 SpectrOMTech.com. All Rights Reserved.
  • 24. Latency Solutions: Transients // get data from transient if (($value = get_transient('my_transient_name')) === false) { // nothing in transient, get from remote API $value = wp_remote_get('http://some-domain.com', $args); // save data from API in transient set_transient('my_transient_name', $value, $expiration); } © 2014 SpectrOMTech.com. All Rights Reserved.
  • 25. Ordering of Conditions if (fastest() || fast() || slowest()) { // some code here } ________________________________________________________________ if (op1() && op2() && op3()) { // more code } © 2014 SpectrOMTech.com. All Rights Reserved.
  • 26. Code Optimized! 1. Practice, practice, practice 2. Always more to learn 3. Balancing act 4. Art form meets science © 2014 SpectrOMTech.com. All Rights Reserved.
  • 27. WP Geek Lab- Give back to WordPress.org Alone we can do so little; together we can do so much. - Helen Keller Connect with us at Hello@SpectrOMTech.com for more info. write code...fix bugs...hangout...talk geek...