PHP & Performance document discusses various techniques to improve PHP and web server performance. Some key points:
- Compilation of PHP scripts can consume significant time, opcode caches like APC reduce this.
- Profiling tools like APD and XDebug help identify bottlenecks in PHP code. Optimizations like output buffering, reducing output, content compression and database tuning can improve performance.
- Server configuration like Apache optimizations for file I/O, syscalls and KeepAlive headers also impact performance. PHP settings like disabling register_globals and using opcaches help.
- Application techniques like avoiding unnecessary functions, using class constants, and reducing regex usage in PHP code provide performance benefits.
Apache and PHP: Why httpd.conf is your new BFF!Jeff Jones
Apache's configuration files can be used to configure how Apache operates, but they can also be used to configure PHP and how Apache httpd interacts with PHP. In this talk, Jeff explains the different ways Apache can be configured, explains many of the useful config options available for Apache modules, including our own mod_php, and showcases example of how they can be used with, and instead of, your PHP code.
How lve stats2 works for you and your customersCloudLinux
LVE Stats2 is a complete re-write of our customer’s statistics module in CloudLinux OS. It features more detailed charts, flexible architecture, and ability to extend the functionality. In this presentation, Igor Seletskiy, our CEO, discusses LVE Stats2.
Slides for my talk at the London Perl Workshop in Nov 2013, featuring the Devel::SizeMe perl module.
See also the screencast at https://archive.org/details/Perl-Memory-Profiling-LPW2013
Apache and PHP: Why httpd.conf is your new BFF!Jeff Jones
Apache's configuration files can be used to configure how Apache operates, but they can also be used to configure PHP and how Apache httpd interacts with PHP. In this talk, Jeff explains the different ways Apache can be configured, explains many of the useful config options available for Apache modules, including our own mod_php, and showcases example of how they can be used with, and instead of, your PHP code.
How lve stats2 works for you and your customersCloudLinux
LVE Stats2 is a complete re-write of our customer’s statistics module in CloudLinux OS. It features more detailed charts, flexible architecture, and ability to extend the functionality. In this presentation, Igor Seletskiy, our CEO, discusses LVE Stats2.
Slides for my talk at the London Perl Workshop in Nov 2013, featuring the Devel::SizeMe perl module.
See also the screencast at https://archive.org/details/Perl-Memory-Profiling-LPW2013
Application Logging in the 21st century - 2014.keyTim Bunce
Slides for my talk at the Austrian Perl Workshop in Salzburg on October 10th.
A video of the talk can be found at https://www.youtube.com/watch?v=4Qj-_eimGuE
Slides for my talk at SkyCon'12 in Limerick.
Here I've squeezed four talks into one, covering a lot of ground quickly, so I've included links to more detailed presentations and other resources.
Slides for my Perl Memory Use talk at YAPC::Asia in Tokyo, September 2012.
(This uploaded version includes quite a few slides from the OSCON version that I skipped at YAPC::Asia in order to have more time for a demo.)
Ansible is the simplest way to automate. MoldCamp, 2015Alex S
Ansible is a radically simple IT automation engine. This is new and great configuration management system (like Chef, Puppet) that has been created in 2012 year. Also Ansible is pretty simple and flexible system, that helps you in managing your servers and execute Ad-hoc commands.
During this session I will explain how to start using Ansible in infrastructure orchestration and what are pros and cons of this system. Also I will explain you our experience in deployments, provisioning and other aspects.
In this talk we will present a middleware async architecture based on Expressive and Swoole to speed up web API development and runtime in PHP. Using this approach, you will be able to achieve great performance improvement, up to 4x faster than nginx or Apache (benchmark).
The why and how of moving to PHP 5.5/5.6Wim Godden
With PHP 5.6 out and many production environments still running 5.2 or 5.3, it's time to paint a clear picture on why everyone should move to 5.5 and 5.6 and how to get code ready for the latest version of PHP. In this talk, we'll look at some handy tools and techniques to ease the migration.
Yesterday I gave presentation on Ansible and it was successful . It give basic understanding of playbook and an example implementation of jboss application from scratch
Devel::NYTProf 2009-07 (OUTDATED, see 201008)Tim Bunce
The slides of my "State-of-the-art Profiling with Devel::NYTProf" talk at OSCON in July 2009.
I'll upload a screencast and give the link in a blog post at http://blog.timbunce.org
This presentation is an introduction to Ansible, an IT automation tool which can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero downtime rolling updates.
Application Logging in the 21st century - 2014.keyTim Bunce
Slides for my talk at the Austrian Perl Workshop in Salzburg on October 10th.
A video of the talk can be found at https://www.youtube.com/watch?v=4Qj-_eimGuE
Slides for my talk at SkyCon'12 in Limerick.
Here I've squeezed four talks into one, covering a lot of ground quickly, so I've included links to more detailed presentations and other resources.
Slides for my Perl Memory Use talk at YAPC::Asia in Tokyo, September 2012.
(This uploaded version includes quite a few slides from the OSCON version that I skipped at YAPC::Asia in order to have more time for a demo.)
Ansible is the simplest way to automate. MoldCamp, 2015Alex S
Ansible is a radically simple IT automation engine. This is new and great configuration management system (like Chef, Puppet) that has been created in 2012 year. Also Ansible is pretty simple and flexible system, that helps you in managing your servers and execute Ad-hoc commands.
During this session I will explain how to start using Ansible in infrastructure orchestration and what are pros and cons of this system. Also I will explain you our experience in deployments, provisioning and other aspects.
In this talk we will present a middleware async architecture based on Expressive and Swoole to speed up web API development and runtime in PHP. Using this approach, you will be able to achieve great performance improvement, up to 4x faster than nginx or Apache (benchmark).
The why and how of moving to PHP 5.5/5.6Wim Godden
With PHP 5.6 out and many production environments still running 5.2 or 5.3, it's time to paint a clear picture on why everyone should move to 5.5 and 5.6 and how to get code ready for the latest version of PHP. In this talk, we'll look at some handy tools and techniques to ease the migration.
Yesterday I gave presentation on Ansible and it was successful . It give basic understanding of playbook and an example implementation of jboss application from scratch
Devel::NYTProf 2009-07 (OUTDATED, see 201008)Tim Bunce
The slides of my "State-of-the-art Profiling with Devel::NYTProf" talk at OSCON in July 2009.
I'll upload a screencast and give the link in a blog post at http://blog.timbunce.org
This presentation is an introduction to Ansible, an IT automation tool which can configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployments or zero downtime rolling updates.
It innovations, impressions & implications-23-jan-2013 at mpste-mumbaiSanjeev Deshmukh
Information Technology is a platform for Innovation. We see many innovations around us wherein IT acts as an enabler. This presentation highlights some of the characteristics of IT, its desirable feature for enabling innovations and in general, its implications for society. Web 2.0 has revolutionized our world view and in turn this has a multiplier effect !
Teaching quality to engineering students is a challenge. They have strong quantitative skills but may lack in soft skills . This presentation is an abridged version of the presentation I gave at ANQ congress in Delhi in 2010. Should we consider students as products of teaching-learning process or customers or co-producers in traversing the quality journey?
Today's high-traffic web sites must implement performance-boosting measures that reduce data processing and reduce load on the database, while increasing the speed of content delivery. One such method is the use of a cache to temporarily store whole pages, database recordsets, large objects, and sessions. While many caching mechanisms exist, memcached provides one of the fastest and easiest-to-use caching servers. Coupling memcached with the alternative PHP cache (APC) can greatly improve performance by reducing data processing time. In this talk, Ben Ramsey covers memcached and the pecl/memcached and pecl/apc extensions for PHP, exploring caching strategies, a variety of configuration options to fine-tune your caching solution, and discusses when it may be appropriate to use memcached vs. APC to cache objects or data.
Caching and tuning fun for high scalabilityWim Godden
Caching has been a 'hot' topic for a few years. But caching takes more than merely taking data and putting it in a cache : the right caching techniques can improve performance and reduce load significantly. But we'll also look at some major pitfalls, showing that caching the wrong way can bring down your site. If you're looking for a clear explanation about various caching techniques and tools like Memcached, Nginx and Varnish, as well as ways to deploy them in an efficient way, this talk is for you.
Caching and tuning fun for high scalabilityWim Godden
Caching has been a 'hot' topic for a few years. But caching takes more than merely taking data and putting it in a cache : the right caching techniques can improve performance and reduce load significantly. But we'll also look at some major pitfalls, showing that caching the wrong way can bring down your site. If you're looking for a clear explanation about various caching techniques and tools like Memcached, Nginx and Varnish, as well as ways to deploy them in an efficient way, this talk is for you.
Pradeep Sharma from OSSCube presents on Securing your web server at OSSCamp, organized by OSSCube - A Global open Source enterprise for Open Source Solutions
To know how we can help your business grow, leveraging Open Source, contact us:
India: +91 995 809 0987
USA: +1 919 791 5427
WEB: www.osscube.com
Mail: sales@osscube.com
How to measure and optimize performance of applications that use Zend Framework 1.x. A talk presented at the New York City Zend Framework Meetup (http://www.meetup.com/ZendFramework-NYCmetro/) on August 23, 2011.
Caching and tuning fun for high scalability @ FOSDEM 2012Wim Godden
Caching has been a 'hot' topic for a few years. But caching takes more than merely taking data and putting it in a cache : the right caching techniques can improve performance and reduce load significantly. But we'll also look at some major pitfalls, showing that caching the wrong way can bring down your site. If you're looking for a clear explanation about various caching techniques and tools like Memcached, Nginx and Varnish, as well as ways to deploy them in an efficient way, this talk is for you.
Caching and tuning fun for high scalabilityWim Godden
Caching has been a 'hot' topic for a few years. But caching takes more than merely taking data and putting it in a cache : the right caching techniques can improve performance and reduce load significantly. But we'll also look at some major pitfalls, showing that caching the wrong way can bring down your site.
If you're looking for a clear explanation about various caching techniques and tools like Memcached, Nginx and Varnish, as well as ways to deploy them in an efficient way, this talk is for you.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
2. 2
• This cycle happens
for every include
file, not just for the
"main" script.
• Compilation can
easily consume
more time than
execution.
PHP Script
Zend Compile
Zend Execute
@
include/require
method
function
call
2
3. Compiler/Opcode Caches
• Each PHP script is compiled 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.
3
5. 5
• For absolute maximum performance, ensure that
all of the software is compiled to take advantage
of the available hardware.
• Enable all compiler optimizations with -O3
• Tune the code to your CPU via -march –mcpu
• CPU specific features -msse –mmmx
-mfpmath=sse
• Drop debug data -fomit-frame-pointer
export CFLAGS="-O3 -msse -mmmx -march=pentium3
-mcpu=pentium3 -funroll-loops -mfpmath=sse
-fomit-frame-pointer"
Compiler Optimizations
5
6. Web Server: File IO
✓ Keep
DirectoryIndex file
list as short as possible.
✓ Whenever possible
disable .htaccess via
AllowOverride
none.
✓ Use Options
FollowSymLinks to
simplify file access
process in Apache.
✓ If logs are
unnecessary disable
them.
✓ If logging is a must,
log everything to 1 file
and break it up during
the analysis stage.
6
7. 7
• Syscall is function executed by the Kernel.
The goal is to minimize the number of these
calls needed to perform a request.
• Do not enable ExtendedStatus.
• For Deny/Allow rules use IPs rather then
domains.
• Do not enable HostnameLookups.
• Keep ServerSignature off
Web Server: Syscalls
7
8. 8
• In theory KeepAlive is supposed to make
things faster, however if not used carefully
it can cripple the server.
• In Apache set KeepAlive timeout,
KeepAliveTimeout as low as possible.
Suggested value: 10 seconds.
• If the server is only serving dynamic
requests, disable KeepAlive all together.
Web Server: KeepAlive
8
9. 9
• 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
Matching Your IO Sizes
PHP Apache OS Client
9
10. 10
• Efficient
• Flexible
• In your script, with ob_start()
• Everywhere, with output_buffering = On
• Improves browser’s rendering speed
PHP: Output Control
PHP Apache
10
11. Apache: Output Control
• The idea is to hand off entire page to the
kernel without blocking.
• Set SendBufferSize = PageSize
Apache OS
11
12. OS: Output Control
OS (Linux)
/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!
OS Client
12
13. 13
• While Apache is great for dynamic requests,
static requests can be served WAY FASTER
by other web servers.
๏ lighttpd
๏ Boa
๏ Tux
๏ thttpd
• For static requests these servers are easily
300-400% faster then Apache 1 or 2.
Static Content Serving
13
14. Less Output == Faster
• Saves server bandwidth (saves $$ too).
• Reduces server resource usage (CPU/
Memory/Disk)
• Pages load faster for clients.
• Reduces network IO high traffic sites,
where it is the primary bottleneck in
most cases.
14
15. 15
• Most browsers support content compression.
• Compressed pages are on average are 6-8 times smaller.
๏ Apache 1 (mod_gzip / mod_deflate)
๏ Apache 2 (mod_deflate)
๏ PHP
‣ From PHP configuration zlib.output_compression=1
‣ From inside the script ob_start(“ob_gzhandler”)
✴ Compression will utilize 3%-5% of CPU.
Content Compression
15
16. Content Reduction
• Use a post-
processor like
Tidy to
remove
formatting,
comments and
CCSify the
code.
<?php
$o = array("clean" => true,
"drop-proprietary-attributes" => true,
"drop-font-tags" => true,
"drop-empty-paras" => true,
"hide-comments" => true,
"join-classes" => true,
"join-styles" => true
);
$tidy = tidy_parse_file("php.html", $o);
tidy_clean_repair($tidy);
echo $tidy;
?>
16
17. 17
➡ register_globals = Off **
➡ magic_quotes_gpc = Off
➡ expose_php = Off
➡ register_argc_argv = Off
➡ always_populate_raw_post_data = Off **
➡ session.use_trans_sid = Off **
➡ session.auto_start = Off **
➡ session.gc_divisor = 1000 or 10000
Tuning PHP Configuration
17
19. 19
• Apache Bench
‣ ab utility bundled with Apache
• Siege
‣ http://www.joedog.org/JoeDog/Siege
• http_load (Excellent for latency tests)
‣ http://www.acme.com/software/http_load/
Testing Web Servers
19
20. Web Server Testing
Concurrency Level: 10
Time taken for tests: 0.265 seconds
Complete requests: 100
Failed requests: 0
Broken pipe errors: 0
Total transferred: 5077082 bytes
HTML transferred: 5061168 bytes
Requests per second: 377.36 [#/sec] (mean)
Time per request: 26.50 [ms] (mean)
Time per request: 2.65 [ms] (mean)
Transfer rate: 19158.80 [Kbytes/sec]
20
21. Latency Test
1000 fetches, 5 max parallel,
2.9648e+07 bytes,
in 0.813035 seconds
29648 mean bytes/connection
1229.96 fetches/sec,
3.64658e+07 bytes/sec
msecs/connect:
0.463202 mean, 12.082 max, 0.045 min
msecs/first-response:
3.12969 mean, 50.783 max, 0.811 min
HTTP response codes:
code 200 -- 1000
1 msec = 0.0001 seconds
21
23. Profiling with APD
• Installation Steps
• pecl install apd
• Modify php.ini
zend_extension=apd.so
Zend Execute
APD Start
APD Finish
Process repeated for
every function/method call
23
24. 24
• Profiling of a script starts from the point when the
apd_set_pprof_trace() function is called.
• All code executed prior, will not be profiled.
$parts = preg_split("!s!", "a b c");
function test(&$var) {
$var = base64_encode(trim($var));
}
apd_set_pprof_trace();
array_walk($parts, 'test');
✴ Use the auto_prepend_file php.ini setting to activate
profiling for an entire application.
Generating A Trace
24
26. 26
• Hard-drive is in most cases the slowest
part of the system, yet all the data
eventually comes from it.
• By adjust the drive configuration
parameters you can help your OS get
the most out of it.
Drive Tuning
26
27. 27
• Use the hdparm utility to adjust
settings.
• -c1 - set IDE 32-bit I/O setting
• -d1 - enable DMA
• -u1 - enable IRQ unmasking
• -m16 - turn on multicount
• -X 34|66|100|133 - transfer mode
Drive Tuning Parameters
27
29. 29
• One way to accelerate File IO operations is by
moving the files and directories to a RAM disk.
• On Linux this is extremely simple to do using via
tmpfs.
# Speed Up /tmp Directory
mount --bind -ttmpfs /tmp /tmp
# Accelerate Scripts Directory
mount --bind -ttmpfs /home/webroot /home/webroot
RAM Disk
29
30. 30
• PHP’s session extension by default stores each
session inside a separate file.
• Many files in one directory reduce access speed.
➡ Assign each user their own session directory
➡ Split sessions into multiple directories
session.save_path = "N;/path"
Session Storage
30
31. Session Storage Alternatives
• File system is slow, lets use memory
• mm - native shared memory storage
• apc - use APC’s store/fetch/delete
• memcache - memory storage daemon
31
35. Use Class Constants
• Parsed at compile time, no execution
overhead.
• Faster lookups due to a smaller hash.
• “Namespacing” & shorter hash names.
• Cleaner code speeds up debugging ;-)
35
36. Avoid Magic
• Magic methods such as __get()/__set()
• Magic loading functions such as
__autoload()
• Dynamic methods via __call()
36
38. • If you absolutely cannot avoid
require_once and include_once use full
paths.
• In PHP 5.2>= this will allow PHP to
avoid opening the file twice.
38
41. Fastest Win32 Detection in the West
• Does not use functions
• Does not care about
WinXP, WinNT, Windows,
Windows98, NT 5.0, etc...
• Always available
$isWindows =
DIRECTORY_SEPARATOR == '';
41
42. What time is it?
Rather then calling time(),
time() and time() again, use
$_SERVER[‘REQUEST_TIME’]
Provides a timestamp, with a
second precision, without any
function calls.
42
44. Use non-capturing patterns
• Placing ?: at the start of a sub-pattern makes it
non-capturing.
• This means PHP/PCRE does not need to
allocate memory to store the matched content
block.
$text = preg_replace( '/=?(?:[^?]+)?/',
'=?iso-8859-1?', $origtext );
$text = preg_replace(
'"/(?:n|t|rn|s)+/"', ' ', $origtext );
44
46. If Possible Avoid Regex
<?php
// Slow
if (preg_match("!^foo_!i", "FoO_")) { }
// Much faster
if (!strncasecmp("foo_", "FoO_", 4)) { }
// Slow
if (preg_match("![a8f9]!", "sometext")) { }
// Faster
if (strpbrk("a8f9", "sometext")) { }
// Slow
if (preg_match("!string!i", "text")) {}
// Faster
if (stripos("text", "string") !== false) {}
46
47. More Regex Avoidance
$text = preg_replace( "/n/", "n", $text);
In this case it would be simpler and to
mention faster to use a regular str_replace()
$text = str_replace( "/n/", "n", $text);
47
49. Use strtr() Properly!
Any ideas on how we can make this code
10 times faster?
$rep = array( '-' => '*', '.' => '*' );
if ( sizeof( $globArr ) > 1 ) {
$glob = "-" . strtr( $globArr[1], $rep );
} else {
$glob = strtr( $globArr[0], $rep );
}
49
50. Use Strings!
Elimination of array operations speeds up
the code and simplifies the internal work
in strtr() function.
if ( sizeof( $globArr ) > 1 ) {
$glob = "-" . strtr( $globArr[1], '-.', '**' );
} else {
$glob = strtr( $globArr[0], '-.', '**' );
}
0 15 30 45 60
4.29
55.70
Seconds
strtr(string)
strtr(array)
50
51. Don’t Replace When you
• Any replacement operation requires
memory, if only to store the “modified”
result.
• A quick strpos() to determine if any
replacement is actually needed can save
memory and improve performance!
51
53. @ operator is evil!
• The error blocking operator, is the most
expensive character in PHP’s alphabet.
• This seemingly innocuous operator
actually performs fairly intensive
operations in the background.
@action();
$old = ini_set(“error_reporting”, 0);
action();
ini_set(“error_reporting”, $old);
53
56. Comparing From An Offset
• As of PHP 5, you don’t need to substr()
string segments from non-start position to
compare them thanks to substr_compare().
if (substr($class, -15) != 'text')
/* == */
if (substr_compare($class, 'text', -15))
56
57. Don’t Mis-use Constants
One of my biggest pet-peeves in PHP is
this kind of nonsense:
$foo = array("bar"=>0);
$foo[bar] = 1;
57
58. Why is this bad?
๏ 1 strtolower
๏ 2 hash lookups
๏ E_NOTICE error message generated
๏ temporary string being created on the
fly.
58
60. Fix “harmless” error messages
‣ Each error results in:
๏ Generation of a complex error string
๏ Output to stdout/stderr
๏ Potential write to a file or syslog
๏ In pre-5.2 releases may leak memory
in some rare instances.
60
61. Simplify for() loop
Avoid function calls within for() loop
control blocks.
<?php
for ( $i = 1; $i < sizeof($array); $i++ ) {}
for ( $i = 0; $i < count($array); $i++ ) {}
for ( $i = 0; $i < strlen($string); $i++ ) {}
Otherwise function is called for every loop
iteration.
61
63. Don’t Re-invent the Wheel
• It is surprising how frequently people try
to re-invent the wheel.
• Now a days PHP has
✓ 2,700 functions
✓ 80 core extensions
✓ 154 PECL extensions
• Chances are what you need already exists!
63
64. Use Full File Paths
• While it is convenient(??) to do require
“foo.php” and have it work, internally
it leads to significant overhead.
• Whenever possible you should use full
paths, that require no resolution in PHP.
64
65. The internals of file ops.
stat64("./b.php", {st_mode=S_IFREG|0644, st_size=6, ...}) = 0
getcwd("/tmp", 4096) = 5
lstat64("/tmp", {st_mode=S_IFDIR|S_ISVTX|0777, st_size=18008, ...}) = 0
lstat64("/tmp/b.php", {st_mode=S_IFREG|0644, st_size=6, ...}) = 0
open("/tmp/b.php", O_RDONLY)
The issue can be further exasperated by
the use of include_path.
65
66. 66
References can be used to simply & accelerate access
to multi-dimensional arrays.
Reference Tricks
$a['b']['c'] = array();
// slow 2 extra hash lookups per access
for($i = 0; $i < 5; $i++)
$a['b']['c'][$i] = $i;
// much faster reference based approach
$ref =& $a['b']['c'];
for($i = 0; $i < 5; $i++)
$ref[$i] = $i;
66
67. Optimization Myths
✦ Removing comments makes code faster
✦ Using “ is faster then ‘
✦ Passing things by-reference makes code
faster
✦ Objects make code faster
✦ Ternary ? : is faster then if () { } else {}
67
68. 68
Caching is the recognition and exploitation of
the fact that most "dynamic" data does not
change every time you request it.
68
69. 69
Most applications will end up using databases
for information storage. Improper use of this
resource can lead to significant and
continually increasing performance loss.
69
70. 70
Most databases offers tools for analyzing
query execution.
EXPLAIN select * from users where login LIKE '%ilia%';
+----------+------+---------------+------+---------+------+-------+------------+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+----------+------+---------------+------+---------+------+-------+------------+
| mm_users | ALL | NULL | NULL | NULL | NULL | 27506 | where used |
+----------+------+---------------+------+---------+------+-------+------------+
EXPLAIN select * from users where login LIKE 'ilia%';
+----------+-------+---------------+-------+---------+------+------+------------+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+----------+-------+---------------+-------+---------+------+------+------------+
| mm_users | range | login | login | 50 | NULL | 2 | where used |
+----------+-------+---------------+-------+---------+------+------+------------+
Check Your Queries
70
71. 71
Rather then creating a column for every Boolean
option, you can pack 32 of them into a single integer
field.
CREATE TABLE users (
is_active INT,
is_banned INT,
is_admin INT,
...
);
CREATE TABLE users (
user_opt INT,
...
);
user_opt & 1 // active
user_opt & 2 // banned
user_opt & 4 // admin
Bitwise Option Packing
71
72. 72
• The simpler the code, the faster it runs,
it really is that simple.
• Syntactic sugar.
• Unnecessary wrappers.
• Wrapping one liners in functions.
• OO for the sake of OO.
KISS = Performance
72
73. Thank You For Listening!
• These slides
• http://www.ilia.ws/
• APC
• http://pecl.php.net/apc
• XDebug
• http://www.xdebug.org/
73
74. Optimizer (Why?)
• The opcodes generated by Zend
Engine are often inefficient.
• Some operations can be avoided
• A lot of temporary vars are not
necessary.
• Every compiler needs an
optimizer ;-)
i
74
76. What Can It Do?
• opt. heredoc
• print to echo
• GLOBALS[foo] to
foo
• inline known
constants
• eliminate NOP
• resolve partial file
paths.
• optionally inline
define() calls
• 60+ function calls
with static values
resolved.
• Much more...
76