SlideShare une entreprise Scribd logo
1  sur  22
Télécharger pour lire hors ligne
Memory Management IN PHP
Writen by: Mahmoud Masih Tehrani
Email:mahmud.tehrani@gmail.com
The golden rule
The number one thing to do when you encounter
(or expect to encounter) memory pressure is: do
not read massive amounts of data in memory at
once if you intend to process them sequentially.
Examples
Do not fetch a large result set in memory as an array; instead, fetch
each row in turn and process it before fetching the next
Do not read large text files in memory (e.g. with file); instead, read
one line at a time
Following this practice religiously will "automatically" take care of
other things for you as well:
There is no longer any need to clean up resources with a big
memory footprint by closing them and losing all references to them
on purpose, because there will be no such resources to begin with
There is no longer a need to unset large variables after you are
done with them, because there will be no such variables as well
Other things to do
Be careful of creating closures inside loops; this
should be easy to do, as creating such inside loops
is a bad code smell. You can always lift the closure
upwards and give it more parameters.
When expecting massive input, design your
program and pick algorithms accordingly. For
example, you can mergesort any amount of text
files of any size using a constant amount of
memory.
Another suggest
When you compute your large array of objects,
try to not compute it all at once. Walk in steps
and process elements as you walk then free
memory and take next elements.
It will take more time, but you can manage the
amount of memory you use.
And Another suggest
You could try profiling it puting some calls to
memory_get_usage(), to look for the place where
it's peaking.
Of course, knowing what the code really does
you'll have more information to reduce its
memory usage.
memory_get_usage
(PHP 4 >= 4.3.2, PHP 5)
memory_get_usage — Returns the amount of
memory allocated to PHP
int memory_get_usage ([ bool $real_usage =
false ] )
Returns the amount of memory, in bytes, that's
currently being allocated to your PHP script.
Returns the memory amount in bytes.
Example #1 A memory_get_usage() example
<?php
// This is only an example, the numbers below will
// differ depending on your system
echo memory_get_usage() . "n"; // 36640
$a = str_repeat("Hello", 4242);
echo memory_get_usage() . "n"; // 57960
unset($a);
echo memory_get_usage() . "n"; // 36744
?>
memory_limit integer
This sets the maximum amount of memory in bytes that a script is
allowed to allocate. This helps prevent poorly written scripts for
eating up all available memory on a server. Note that to have no
memory limit, set this directive to -1.
Prior to PHP 5.2.1, in order to use this directive it had to be enabled
at compile time by using --enable-memory-limit in the configure line.
This compile-time flag was also required to define the functions
memory_get_usage() and memory_get_peak_usage() prior to 5.2.1.
When an integer is used, the value is measured in bytes. Shorthand
notation, as described in this FAQ, may also be used.
See also: max_execution_time.
Memory Management
In C, you always have to worry about memory
management. This still holds true when writing
PHP extensions in C, but the extension API
provides you with a safety net and some helpful
debugging facilities if you use the API's memory-
management wrapper functions (you are strongly
encouraged to do so).
The most important of its features for the Hacker,
and the first thing to mention is tracking
allocations. Tracking allocations allow the
memory manager to avoid leaks, a thorn in the
side of most Hackers. When PHP is built in debug
mode (--enable-debug), detected leaks are
reported, in a perfect world they would never get
to deployment.
The wrapper functions are
● emalloc( )
● efree( )
● estrdup( )
● estrndup( )
● ecalloc( )
● erealloc( )
One of the features you get by using emalloc( ) is a
safety net for memory leaks. If you emalloc( )
something and forget to efree( ) it, PHP prints a leak
warning like this if you are running in debug mode
(enabled by compiling PHP with the --enable-debug
switch):
foo.c(123) : Freeing 0x0821E5FC (20 bytes),
script=foo.php
Last leak repeated 1 time
If you efree( ) something that was allocated using malloc( ) or some mechanism
other than the PHP memory-management functions, you get the following:
---------------------------------------
foo.c(124) : Block 0x08219C94 status:
Beginning: Overrun (magic=0x00000000, expected=0x7312F8DC)
End: Unknown
---------------------------------------
foo.c(124) : Block 0x0821EB1C status:
Beginning: Overrun (magic=0x00000000, expected=0x7312F8DC)
End: Unknown
---------------------------------------
In this case, line 124 in foo.c is the call to efree( ). PHP
knows it didn't allocate this memory because it didn't
contain the magic token that indicates a PHP allocation.
The emalloc( )/efree( ) safety net also catches overruns—
e.g., if you emalloc(20) but write 21 bytes to that address.
For example:
123: s = emalloc(6);
124: strcpy(s,"Rasmus");
125: efree(s);
Because this code failed to allocate enough memory to hold the string and the terminating
NULL, PHP prints this warning:
---------------------------------------
foo.c(125) : Block 0x08219CB8 status:
Beginning: OK (allocated on foo.c:123, 6 bytes)
End: Overflown (magic=0x2A8FCC00 instead of 0x2A8FCC84)
1 byte(s) overflown
---------------------------------------
foo.c(125) : Block 0x08219C40 status:
Beginning: OK (allocated on foo.c:123, 6 bytes)
End: Overflown (magic=0x2A8FCC00 instead of 0x2A8FCC84)
1 byte(s) overflown
---------------------------------------
The warning shows where the overflowed
memory was allocated (line 123) and where this
overflow was detected (line 125 in the efree( )
call).
These memory-handling functions can catch a lot of
silly little mistakes that might otherwise waste your
time, so do your development with the debug switch
enabled. Don't forget to recompile in non-debug mode
when you are done testing, though, as the various tests
done by the emalloc( ) type functions slow down PHP.
An extension compiled in debug mode does not work in an
instance of PHP not compiled in debug mode. When PHP
loads an extension, it checks to see if the debug setting, the
thread-safety setting, and the API version all match. If
something doesn't match, you will get a warning like this:
Warning: foo: Unable to initialize module
Module compiled with debug=0, thread-safety=0 module
API=20010901
PHP compiled with debug=1, thread-safety=0 module
API=20010901
If you compile the Apache module version of PHP with
the --enable-memory-limit switch, it will add the
script's peak memory usage to the Apache r->notes
table. You can access this information from other
Apache modules, such as mod_log_config. Add this
string to your Apache LogFormat line to log the peak
number of bytes a script used:
%{mod_php_memory_usage}n
If you're having problems with a module allocating too
much memory and grinding your system into the ground,
build PHP with the memory-limit option enabled. This
makes PHP heed the memory_limit directive in your php.ini
file, terminating a script if it tries to allocate more memory
than the specified limit. This results in errors like this:
Fatal error: Allowed memory size of 102400 bytes
exhausted at ...
(tried to allocate 46080 bytes) in /path/script.php on line
35
refrence
● http://php.net/manual/en/internals2.memory.
php
● http://docstore.mik.ua/orelly/webprog/php/ch
14_05.htm
● http://stackoverflow.com/questions/7517389/b
est-practices-for-managing-memory-in-a-php-
script

Contenu connexe

Dernier

4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...DhatriParmar
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 

Dernier (20)

4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
Beauty Amidst the Bytes_ Unearthing Unexpected Advantages of the Digital Wast...
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"Mattingly "AI & Prompt Design: Large Language Models"
Mattingly "AI & Prompt Design: Large Language Models"
 

En vedette

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

En vedette (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Memory managment php (english)

  • 1. Memory Management IN PHP Writen by: Mahmoud Masih Tehrani Email:mahmud.tehrani@gmail.com
  • 2. The golden rule The number one thing to do when you encounter (or expect to encounter) memory pressure is: do not read massive amounts of data in memory at once if you intend to process them sequentially.
  • 3. Examples Do not fetch a large result set in memory as an array; instead, fetch each row in turn and process it before fetching the next Do not read large text files in memory (e.g. with file); instead, read one line at a time Following this practice religiously will "automatically" take care of other things for you as well: There is no longer any need to clean up resources with a big memory footprint by closing them and losing all references to them on purpose, because there will be no such resources to begin with There is no longer a need to unset large variables after you are done with them, because there will be no such variables as well
  • 4. Other things to do Be careful of creating closures inside loops; this should be easy to do, as creating such inside loops is a bad code smell. You can always lift the closure upwards and give it more parameters. When expecting massive input, design your program and pick algorithms accordingly. For example, you can mergesort any amount of text files of any size using a constant amount of memory.
  • 5. Another suggest When you compute your large array of objects, try to not compute it all at once. Walk in steps and process elements as you walk then free memory and take next elements. It will take more time, but you can manage the amount of memory you use.
  • 6. And Another suggest You could try profiling it puting some calls to memory_get_usage(), to look for the place where it's peaking. Of course, knowing what the code really does you'll have more information to reduce its memory usage.
  • 7. memory_get_usage (PHP 4 >= 4.3.2, PHP 5) memory_get_usage — Returns the amount of memory allocated to PHP int memory_get_usage ([ bool $real_usage = false ] ) Returns the amount of memory, in bytes, that's currently being allocated to your PHP script. Returns the memory amount in bytes.
  • 8. Example #1 A memory_get_usage() example <?php // This is only an example, the numbers below will // differ depending on your system echo memory_get_usage() . "n"; // 36640 $a = str_repeat("Hello", 4242); echo memory_get_usage() . "n"; // 57960 unset($a); echo memory_get_usage() . "n"; // 36744 ?>
  • 9. memory_limit integer This sets the maximum amount of memory in bytes that a script is allowed to allocate. This helps prevent poorly written scripts for eating up all available memory on a server. Note that to have no memory limit, set this directive to -1. Prior to PHP 5.2.1, in order to use this directive it had to be enabled at compile time by using --enable-memory-limit in the configure line. This compile-time flag was also required to define the functions memory_get_usage() and memory_get_peak_usage() prior to 5.2.1. When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used. See also: max_execution_time.
  • 10. Memory Management In C, you always have to worry about memory management. This still holds true when writing PHP extensions in C, but the extension API provides you with a safety net and some helpful debugging facilities if you use the API's memory- management wrapper functions (you are strongly encouraged to do so).
  • 11. The most important of its features for the Hacker, and the first thing to mention is tracking allocations. Tracking allocations allow the memory manager to avoid leaks, a thorn in the side of most Hackers. When PHP is built in debug mode (--enable-debug), detected leaks are reported, in a perfect world they would never get to deployment.
  • 12. The wrapper functions are ● emalloc( ) ● efree( ) ● estrdup( ) ● estrndup( ) ● ecalloc( ) ● erealloc( )
  • 13. One of the features you get by using emalloc( ) is a safety net for memory leaks. If you emalloc( ) something and forget to efree( ) it, PHP prints a leak warning like this if you are running in debug mode (enabled by compiling PHP with the --enable-debug switch): foo.c(123) : Freeing 0x0821E5FC (20 bytes), script=foo.php Last leak repeated 1 time
  • 14. If you efree( ) something that was allocated using malloc( ) or some mechanism other than the PHP memory-management functions, you get the following: --------------------------------------- foo.c(124) : Block 0x08219C94 status: Beginning: Overrun (magic=0x00000000, expected=0x7312F8DC) End: Unknown --------------------------------------- foo.c(124) : Block 0x0821EB1C status: Beginning: Overrun (magic=0x00000000, expected=0x7312F8DC) End: Unknown ---------------------------------------
  • 15. In this case, line 124 in foo.c is the call to efree( ). PHP knows it didn't allocate this memory because it didn't contain the magic token that indicates a PHP allocation. The emalloc( )/efree( ) safety net also catches overruns— e.g., if you emalloc(20) but write 21 bytes to that address. For example: 123: s = emalloc(6); 124: strcpy(s,"Rasmus"); 125: efree(s);
  • 16. Because this code failed to allocate enough memory to hold the string and the terminating NULL, PHP prints this warning: --------------------------------------- foo.c(125) : Block 0x08219CB8 status: Beginning: OK (allocated on foo.c:123, 6 bytes) End: Overflown (magic=0x2A8FCC00 instead of 0x2A8FCC84) 1 byte(s) overflown --------------------------------------- foo.c(125) : Block 0x08219C40 status: Beginning: OK (allocated on foo.c:123, 6 bytes) End: Overflown (magic=0x2A8FCC00 instead of 0x2A8FCC84) 1 byte(s) overflown ---------------------------------------
  • 17. The warning shows where the overflowed memory was allocated (line 123) and where this overflow was detected (line 125 in the efree( ) call).
  • 18. These memory-handling functions can catch a lot of silly little mistakes that might otherwise waste your time, so do your development with the debug switch enabled. Don't forget to recompile in non-debug mode when you are done testing, though, as the various tests done by the emalloc( ) type functions slow down PHP.
  • 19. An extension compiled in debug mode does not work in an instance of PHP not compiled in debug mode. When PHP loads an extension, it checks to see if the debug setting, the thread-safety setting, and the API version all match. If something doesn't match, you will get a warning like this: Warning: foo: Unable to initialize module Module compiled with debug=0, thread-safety=0 module API=20010901 PHP compiled with debug=1, thread-safety=0 module API=20010901
  • 20. If you compile the Apache module version of PHP with the --enable-memory-limit switch, it will add the script's peak memory usage to the Apache r->notes table. You can access this information from other Apache modules, such as mod_log_config. Add this string to your Apache LogFormat line to log the peak number of bytes a script used: %{mod_php_memory_usage}n
  • 21. If you're having problems with a module allocating too much memory and grinding your system into the ground, build PHP with the memory-limit option enabled. This makes PHP heed the memory_limit directive in your php.ini file, terminating a script if it tries to allocate more memory than the specified limit. This results in errors like this: Fatal error: Allowed memory size of 102400 bytes exhausted at ... (tried to allocate 46080 bytes) in /path/script.php on line 35
  • 22. refrence ● http://php.net/manual/en/internals2.memory. php ● http://docstore.mik.ua/orelly/webprog/php/ch 14_05.htm ● http://stackoverflow.com/questions/7517389/b est-practices-for-managing-memory-in-a-php- script