SlideShare a Scribd company logo
1 of 41
PHP Performance 101:
so you need to use a database
Leon Fayer
@papa_fire
Who am I ?
• 20+ years development and operations of web applications
• currently Vice President at OmniTI
• can be found online:
• @papa_fire
• github:lfayer
• http://fayerplay.com
• https://joind.in/talk/view/11914
what it is about
databases & performance
what it’s not about
NoSQL MySQL
how database connection works
① establish connection
② send query
③ process query
④ send result
⑤ close connection
common database connection
$dbh = new DB(…);
$sth = $dbh->prepare($query);
$sth->execute();
$result = $sth->fetchAll();
$dbh = null;
common database connection
① var $dbh = new DB(…);
② var $sth = $dbh->prepare($query);
① $sth->execute();
② var $result = $sth->fetchAll();
③ $dbh = null;
① establish connection
① establish connection
⑤ close connection
and
problem
connection overhead
visual representation
①
①
①
⑤
⑤
⑤
short answer
persistent connections
short and helpful answer
persistent connections
avoid multiple connections
how it works (high level)
①
①
①
⑤
⑤
⑤
①
⑤
conclusion
reduce # of connections
② send query
most common problem
n+1
n+1
// get a list of items
$sth = $dbh->prepare("select item_id from items
where active = true");
$sth->execute();
$items = $sth->fetchAll();
// get properties for each items
foreach ($items as $i) {
$sth_prop = $dbh->prepare("select * from
item_properties where item_id = ?");
$sth_prop->execute($item);
$item_list[$i[‘item_id’]][‘props’] = $sth_prop->fetchAll();
$item_list[$i[‘item_id’]][‘id’] = $i[‘id’];
}
n+1 you don’t know about
// get a list of items
$items = get_active_item_ids();
// get properties for each items
foreach ($items as $i) {
$item = Item->new($i[‘item_id’])
$item_list[$i[‘item_id’][‘id’] = $item->item_id;
$item_list[$i[‘item_id’]][‘props’] = $item->properties();
}
easy solution
// get a list of items with properties
$sth = $dbh->prepare("select i. item_id, p.* from items i,
item_properties p
where i.item_id = p.item_id
and active = true");
$sth->execute();
$items = $sth->fetchAll();
// arrange object to your liking
foreach ($items as $i) {
$item_list[$i[‘item_id’]][‘props’] = $i;
$item_list[$i[‘item_id’]][‘id’] = $i[‘id’];
}
conclusion
limit number of queries
cool stuff
:BONUS:
Common Table Expressions
(CTEs)
* MySQL does not support CTEs
// create temp table naughty_users
// and get data from it
with naughty_users as (
select * from users where banned = 1
)
select userid, email from naughty_users;
even more cool
Writeable
Common Table Expressions
* Postgres 9.1+ only
multiple queries are required
// create user record
insert into users (name, email) values (?,?) returning
userid
// create address record
insert into addresses (userid, address, city, state,
zip) values (?,?,?,?,?) returning addressid
// track changes to user information
insert into user_history (userid, addressid, action)
values (?,?,?) returning historyid
or are they?
with userdata as (
insert into users (name, email) values (?,?)
returning userid
), addressdata as (
insert into addresses (userid, address, city, state, zip)
select userid,?,?,?,? from userdata
returning addressid
), historydata as (
insert into user_history (userid, addressid, action)
select userid, addressid,?
from userdata, addressdata
returning historyid
)
select userid, addressid, historyid
from userdata, addressdata, historydata;
why not use transactions?
• no complicated transaction code
• no complicated error handling code
• reduced query overhead
• better performance
find out more
For more details:
http://omniti.com/seeds/writable-ctes-improve-performance
③ process query
unpopular opinion
ORMs are evil
why?
1. machine-generated
2. object construction overhead
3. false sense of control
in one sentence
you have no idea how it works
timely tweet
conclusion
learn SQL
④ send results
may be shocking, but …
databases can do math
illustrating wrong
// get all orders
$sth = $dbh->prepare("select order_id, price from orders");
$sth->execute();
$orders= $sth->fetchAll();
//order by order_id
usort($orders, function ($a, $b) { if ($a['order_id'] == $b['order_id']) { return 0; }
return $a['order_id'] < $b['order_id'] ? -1 : 1; });
// get average $ for last 10 orders
$count = 1;
$total = 0;
$avg = 0;
foreach ($orders as $order) {
$total += $order[‘price’];
if ($count == 10) {
$avg = $total/$count;
break 1;
}
$count++;
}
vs right
// get average $ for last 10 orders
$sth = $dbh->prepare("select avg(price) as avg_price
from (select price from orders
order by order_id desc limit 10) ");
$sth->execute();
$orders= $sth->fetchAll();
$avg = $orders[‘avg_price’];
conclusion
learn SQL
other things to consider
1. cache is a wonderful thing
2. * is not your friend
3. EXPLAIN/ANALYZE are
Questions?

More Related Content

What's hot

[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018Adam Tomat
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012l3rady
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressAlena Holligan
 
Manage catalog Configueation In Sharepoint PowerShell
Manage catalog Configueation In Sharepoint PowerShellManage catalog Configueation In Sharepoint PowerShell
Manage catalog Configueation In Sharepoint PowerShellChitexe Marcos Maniche
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel16.mysql stored procedures in laravel
16.mysql stored procedures in laravelRazvan Raducanu, PhD
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryl3rady
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Workhorse Computing
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Getting Creative with WordPress Queries
Getting Creative with WordPress QueriesGetting Creative with WordPress Queries
Getting Creative with WordPress QueriesDrewAPicture
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntityBasuke Suzuki
 
Writing Maintainable Perl
Writing Maintainable PerlWriting Maintainable Perl
Writing Maintainable Perltinypigdotcom
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxMichelangelo van Dam
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway ichikaway
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Fwdays
 

What's hot (20)

[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018[WLDN] Supercharging word press development in 2018
[WLDN] Supercharging word press development in 2018
 
You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012You don’t know query - WordCamp UK Edinburgh 2012
You don’t know query - WordCamp UK Edinburgh 2012
 
WordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPressWordCamp Portland 2018: PHP for WordPress
WordCamp Portland 2018: PHP for WordPress
 
Php functions
Php functionsPhp functions
Php functions
 
Manage catalog Configueation In Sharepoint PowerShell
Manage catalog Configueation In Sharepoint PowerShellManage catalog Configueation In Sharepoint PowerShell
Manage catalog Configueation In Sharepoint PowerShell
 
Perl6 grammars
Perl6 grammarsPerl6 grammars
Perl6 grammars
 
16.mysql stored procedures in laravel
16.mysql stored procedures in laravel16.mysql stored procedures in laravel
16.mysql stored procedures in laravel
 
WordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know queryWordPress London 16 May 2012 - You don’t know query
WordPress London 16 May 2012 - You don’t know query
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
Neatly folding-a-tree
Neatly folding-a-treeNeatly folding-a-tree
Neatly folding-a-tree
 
Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.Perl6 Regexen: Reduce the line noise in your code.
Perl6 Regexen: Reduce the line noise in your code.
 
Intoduction to php restful web service
Intoduction to php  restful web serviceIntoduction to php  restful web service
Intoduction to php restful web service
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Session8
Session8Session8
Session8
 
Getting Creative with WordPress Queries
Getting Creative with WordPress QueriesGetting Creative with WordPress Queries
Getting Creative with WordPress Queries
 
Introducing CakeEntity
Introducing CakeEntityIntroducing CakeEntity
Introducing CakeEntity
 
Writing Maintainable Perl
Writing Maintainable PerlWriting Maintainable Perl
Writing Maintainable Perl
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
Tips of CakePHP and MongoDB - Cakefest2011 ichikaway
 
Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"Pim Elshoff "Final Class Aggregate"
Pim Elshoff "Final Class Aggregate"
 

Similar to PHP performance 101: so you need to use a database

Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Michelangelo van Dam
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Michelangelo van Dam
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Mike Schinkel
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedKazuho Oku
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress DeveloperJoey Kudish
 
Neo4j: Import and Data Modelling
Neo4j: Import and Data ModellingNeo4j: Import and Data Modelling
Neo4j: Import and Data ModellingNeo4j
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responsesdarrelmiller71
 
The Myths, Musts and Migraines of Migrations - DrupalJam 2018
The Myths, Musts and Migraines of Migrations - DrupalJam 2018The Myths, Musts and Migraines of Migrations - DrupalJam 2018
The Myths, Musts and Migraines of Migrations - DrupalJam 2018LimoenGroen
 
10 wp7 local database
10 wp7   local database10 wp7   local database
10 wp7 local databaseTao Wang
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Adam Tomat
 
Intro to php
Intro to phpIntro to php
Intro to phpSp Singh
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applicationselliando dias
 
Evolutionary db development
Evolutionary db development Evolutionary db development
Evolutionary db development Open Party
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Victor Rentea
 
Improve Your Salesforce Efficiency: Formulas for the Everyday Admin
Improve Your Salesforce Efficiency: Formulas for the Everyday AdminImprove Your Salesforce Efficiency: Formulas for the Everyday Admin
Improve Your Salesforce Efficiency: Formulas for the Everyday AdminEve Lyons-Berg
 

Similar to PHP performance 101: so you need to use a database (20)

Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012Quality Assurance for PHP projects - ZendCon 2012
Quality Assurance for PHP projects - ZendCon 2012
 
Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12Workshop quality assurance for php projects tek12
Workshop quality assurance for php projects tek12
 
QA for PHP projects
QA for PHP projectsQA for PHP projects
QA for PHP projects
 
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
Hardcore URL Routing for WordPress - WordCamp Atlanta 2014 (PPT)
 
JSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons LearnedJSON SQL Injection and the Lessons Learned
JSON SQL Injection and the Lessons Learned
 
Becoming a better WordPress Developer
Becoming a better WordPress DeveloperBecoming a better WordPress Developer
Becoming a better WordPress Developer
 
Neo4j: Import and Data Modelling
Neo4j: Import and Data ModellingNeo4j: Import and Data Modelling
Neo4j: Import and Data Modelling
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
The Myths, Musts and Migraines of Migrations - DrupalJam 2018
The Myths, Musts and Migraines of Migrations - DrupalJam 2018The Myths, Musts and Migraines of Migrations - DrupalJam 2018
The Myths, Musts and Migraines of Migrations - DrupalJam 2018
 
10 wp7 local database
10 wp7   local database10 wp7   local database
10 wp7 local database
 
Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019Supercharging WordPress Development - Wordcamp Brighton 2019
Supercharging WordPress Development - Wordcamp Brighton 2019
 
Intro to php
Intro to phpIntro to php
Intro to php
 
PHP and Rich Internet Applications
PHP and Rich Internet ApplicationsPHP and Rich Internet Applications
PHP and Rich Internet Applications
 
Unit testing zend framework apps
Unit testing zend framework appsUnit testing zend framework apps
Unit testing zend framework apps
 
Php summary
Php summaryPhp summary
Php summary
 
Evolutionary db development
Evolutionary db development Evolutionary db development
Evolutionary db development
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7ElePHPant7 - Introduction to PHP7
ElePHPant7 - Introduction to PHP7
 
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
Evolving a Clean, Pragmatic Architecture at JBCNConf 2019
 
Improve Your Salesforce Efficiency: Formulas for the Everyday Admin
Improve Your Salesforce Efficiency: Formulas for the Everyday AdminImprove Your Salesforce Efficiency: Formulas for the Everyday Admin
Improve Your Salesforce Efficiency: Formulas for the Everyday Admin
 

More from Leon Fayer

What kids can teach us about building effective teams
What kids can teach us about building effective teamsWhat kids can teach us about building effective teams
What kids can teach us about building effective teamsLeon Fayer
 
Как измерить успех
Как измерить успехКак измерить успех
Как измерить успехLeon Fayer
 
Building the right architecture for you
Building the right architecture for youBuilding the right architecture for you
Building the right architecture for youLeon Fayer
 
Lost art of troubleshooting
Lost art of troubleshootingLost art of troubleshooting
Lost art of troubleshootingLeon Fayer
 
Adventures in public speaking
Adventures in public speakingAdventures in public speaking
Adventures in public speakingLeon Fayer
 
BizOps and you
BizOps and youBizOps and you
BizOps and youLeon Fayer
 
On call for developers
On call for developersOn call for developers
On call for developersLeon Fayer
 
Production testing through monitoring
Production testing through monitoringProduction testing through monitoring
Production testing through monitoringLeon Fayer
 
What DevOps is Not
What DevOps is NotWhat DevOps is Not
What DevOps is NotLeon Fayer
 
Breaking social dependency
Breaking social dependencyBreaking social dependency
Breaking social dependencyLeon Fayer
 
Improving DevOps through better monitoring
Improving DevOps through better monitoringImproving DevOps through better monitoring
Improving DevOps through better monitoringLeon Fayer
 

More from Leon Fayer (12)

What kids can teach us about building effective teams
What kids can teach us about building effective teamsWhat kids can teach us about building effective teams
What kids can teach us about building effective teams
 
Как измерить успех
Как измерить успехКак измерить успех
Как измерить успех
 
Bias in tech
Bias in techBias in tech
Bias in tech
 
Building the right architecture for you
Building the right architecture for youBuilding the right architecture for you
Building the right architecture for you
 
Lost art of troubleshooting
Lost art of troubleshootingLost art of troubleshooting
Lost art of troubleshooting
 
Adventures in public speaking
Adventures in public speakingAdventures in public speaking
Adventures in public speaking
 
BizOps and you
BizOps and youBizOps and you
BizOps and you
 
On call for developers
On call for developersOn call for developers
On call for developers
 
Production testing through monitoring
Production testing through monitoringProduction testing through monitoring
Production testing through monitoring
 
What DevOps is Not
What DevOps is NotWhat DevOps is Not
What DevOps is Not
 
Breaking social dependency
Breaking social dependencyBreaking social dependency
Breaking social dependency
 
Improving DevOps through better monitoring
Improving DevOps through better monitoringImproving DevOps through better monitoring
Improving DevOps through better monitoring
 

Recently uploaded

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
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 educationjfdjdjcjdnsjd
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 

Recently uploaded (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

PHP performance 101: so you need to use a database

  • 1. PHP Performance 101: so you need to use a database Leon Fayer @papa_fire
  • 2. Who am I ? • 20+ years development and operations of web applications • currently Vice President at OmniTI • can be found online: • @papa_fire • github:lfayer • http://fayerplay.com • https://joind.in/talk/view/11914
  • 3. what it is about databases & performance
  • 4. what it’s not about NoSQL MySQL
  • 5. how database connection works ① establish connection ② send query ③ process query ④ send result ⑤ close connection
  • 6. common database connection $dbh = new DB(…); $sth = $dbh->prepare($query); $sth->execute(); $result = $sth->fetchAll(); $dbh = null;
  • 7. common database connection ① var $dbh = new DB(…); ② var $sth = $dbh->prepare($query); ① $sth->execute(); ② var $result = $sth->fetchAll(); ③ $dbh = null;
  • 9. ① establish connection ⑤ close connection and
  • 13. short and helpful answer persistent connections avoid multiple connections
  • 14. how it works (high level) ① ① ① ⑤ ⑤ ⑤ ① ⑤
  • 15. conclusion reduce # of connections
  • 18. n+1 // get a list of items $sth = $dbh->prepare("select item_id from items where active = true"); $sth->execute(); $items = $sth->fetchAll(); // get properties for each items foreach ($items as $i) { $sth_prop = $dbh->prepare("select * from item_properties where item_id = ?"); $sth_prop->execute($item); $item_list[$i[‘item_id’]][‘props’] = $sth_prop->fetchAll(); $item_list[$i[‘item_id’]][‘id’] = $i[‘id’]; }
  • 19. n+1 you don’t know about // get a list of items $items = get_active_item_ids(); // get properties for each items foreach ($items as $i) { $item = Item->new($i[‘item_id’]) $item_list[$i[‘item_id’][‘id’] = $item->item_id; $item_list[$i[‘item_id’]][‘props’] = $item->properties(); }
  • 20. easy solution // get a list of items with properties $sth = $dbh->prepare("select i. item_id, p.* from items i, item_properties p where i.item_id = p.item_id and active = true"); $sth->execute(); $items = $sth->fetchAll(); // arrange object to your liking foreach ($items as $i) { $item_list[$i[‘item_id’]][‘props’] = $i; $item_list[$i[‘item_id’]][‘id’] = $i[‘id’]; }
  • 22. cool stuff :BONUS: Common Table Expressions (CTEs) * MySQL does not support CTEs
  • 23. // create temp table naughty_users // and get data from it with naughty_users as ( select * from users where banned = 1 ) select userid, email from naughty_users;
  • 24. even more cool Writeable Common Table Expressions * Postgres 9.1+ only
  • 25. multiple queries are required // create user record insert into users (name, email) values (?,?) returning userid // create address record insert into addresses (userid, address, city, state, zip) values (?,?,?,?,?) returning addressid // track changes to user information insert into user_history (userid, addressid, action) values (?,?,?) returning historyid
  • 26. or are they? with userdata as ( insert into users (name, email) values (?,?) returning userid ), addressdata as ( insert into addresses (userid, address, city, state, zip) select userid,?,?,?,? from userdata returning addressid ), historydata as ( insert into user_history (userid, addressid, action) select userid, addressid,? from userdata, addressdata returning historyid ) select userid, addressid, historyid from userdata, addressdata, historydata;
  • 27. why not use transactions? • no complicated transaction code • no complicated error handling code • reduced query overhead • better performance
  • 28. find out more For more details: http://omniti.com/seeds/writable-ctes-improve-performance
  • 31. why? 1. machine-generated 2. object construction overhead 3. false sense of control
  • 32. in one sentence you have no idea how it works
  • 36. may be shocking, but … databases can do math
  • 37. illustrating wrong // get all orders $sth = $dbh->prepare("select order_id, price from orders"); $sth->execute(); $orders= $sth->fetchAll(); //order by order_id usort($orders, function ($a, $b) { if ($a['order_id'] == $b['order_id']) { return 0; } return $a['order_id'] < $b['order_id'] ? -1 : 1; }); // get average $ for last 10 orders $count = 1; $total = 0; $avg = 0; foreach ($orders as $order) { $total += $order[‘price’]; if ($count == 10) { $avg = $total/$count; break 1; } $count++; }
  • 38. vs right // get average $ for last 10 orders $sth = $dbh->prepare("select avg(price) as avg_price from (select price from orders order by order_id desc limit 10) "); $sth->execute(); $orders= $sth->fetchAll(); $avg = $orders[‘avg_price’];
  • 40. other things to consider 1. cache is a wonderful thing 2. * is not your friend 3. EXPLAIN/ANALYZE are