SlideShare una empresa de Scribd logo
1 de 30
© 2017 Magento, Inc. Page | 1 ‘17
СПОСОБЫ ОПТИМИЗАЦИИ
И РАБОТА С ПАМЯТЬЮ
В MAGENTO 2
© 2017 Magento, Inc. Page | 2 ‘17
Разработчики в компании «Amasty»
Обуховский Евгений
Харлап Станислав
© 2017 Magento, Inc. Page | 3 ‘17
ИСПОЛЬЗОВАНИЕ
ПАМЯТИ В PHP
© 2017 Magento, Inc. Page | 4 ‘17
© 2017 Magento, Inc. Page | 5 ‘17
ПИКОВОЕ ЗНАЧЕНИЕ
ИСПОЛЬЗУЕМОЙ ПАМЯТИ В КБ
тестовое веб-приложение с запросами к БД
© 2017 Magento, Inc. Page | 6 ‘17
ПАМЯТЬ И МАССИВЫ
<?php
$startMemory = memory_get_usage();
$array = range(1, 100000);
echo memory_get_usage() - $startMemory, ' bytes';
© 2017 Magento, Inc. Page | 7 ‘17
ОЧЕВИДНЫЙ
ОТВЕТ
800 000 байт
Около 780 Кб
© 2017 Magento, Inc. Page | 8 ‘17
4,00 Мб
ПРАВИЛЬНЫЙ
ОТВЕТ
В 5 раз больше ожидаемого результата
© 2017 Magento, Inc. Page | 9 ‘17
СТРУКТУРА ЭЛЕМЕНТА МАССИВА
typedef struct _Bucket {
zend_ulong h;
zend_string *key;
zval val;
} Bucket;
© 2017 Magento, Inc. Page | 10 ‘17
struct _zval_struct {
zend_value value;
union {
struct {
...
} v;
uint32_t type_info;
} u1;
union u2;
};
typedef union _zend_value {
zend_long lval;
double dval;
zend_refcounted *counted;
zend_string *str;
zend_array *arr;
zend_object *obj;
zend_resource *res;
zend_reference *ref;
zend_ast_ref *ast;
zval *zv;
void *ptr;
zend_class_entry *ce;
zend_function *func;
struct {
...
} ww;
} zend_value;
СТРУКТУРА ЭЛЕМЕНТА МАССИВА
© 2017 Magento, Inc. Page | 11 ‘17
ХРАНЕНИЕ МАССИВА. ИТОГИ.
х64 х32
PHP 7 42 байт * 100 000 30 байт * 100 000
ИТОГ 4 Мб 3 Мб
PHP 5.6 или меньше 144 байт * 100 000 76 байт * 100 000
ИТОГ 14 Мб 7.4 Мб
© 2017 Magento, Inc. Page | 12 ‘17
UNSET VS ПРИРАВНИВАНИЕ К NULL
function memoryUsage($usage, $base_memory_usage) {
printf("Bytes diff: %dn", $usage - $base_memory_usage); }
$baseUsage = memory_get_usage();
$a = someBigValue();
unset($a);
memoryUsage(memory_get_usage(), $baseUsage);
$baseUsage = memory_get_usage();
$a = someBigValue();
$a = null;
memoryUsage(memory_get_usage(), $baseUsage);
Bytes
diff: 0
Bytes
diff: 76
© 2017 Magento, Inc. Page | 13 ‘17
<?php
$startMemoryUsage = memory_get_usage();
$bigValue = str_repeat('BIG-BIG STRINGGGGGGGG',1024);
$a = array($bigValue, $bigValue, $bigValue, $bigValue);
foreach ($a as $k => $v) {
$a[$k] = $bigValue;
unset($k, $v);
Printf("Bytes: %dn", memory_get_usage() –
$startMemoryUsage);
}
echo 'After Foreach.' . PHP_EOL;
Printf("Bytes: %dn", memory_get_usage() –
$startMemoryUsage);
?>
ПЕРЕДАЧА МАССИВОВ ПО ССЫЛКЕ
Before Foreach
Bytes: 61940
Bytes: 77632
Bytes: 93032
Bytes: 108432
Bytes: 123832
After Foreach
Bytes: 61940
© 2017 Magento, Inc. Page | 14 ‘17
foreach ($a as $k => &$v) {
$a[$k] = $bigValue;
unset($k, $v);
Printf("Bytes: %dn", memory_get_usage() - $startMemoryUsage);
}
ПЕРЕДАЧА МАССИВОВ ПО ССЫЛКЕ
Bytes: 61940
Bytes: 61940
Bytes: 61940
Bytes: 61940
AFTER FOREACH
BYTES: 61940
© 2017 Magento, Inc. Page | 15 ‘17
© 2017 Magento, Inc. Page | 16 ‘17
SPL FIXED ARRAY
<?php $startMemory = memory_get_usage();
$array = new SplFixedArray(100000);
for ($i = 0; $i < 100000; ++$i) {
$array[$i] = $i;
}
Достигается тем, что SplFixedArray не нуждается в
bucket структуре, только один zval и один указатель
для каждого элемента.
© 2017 Magento, Inc. Page | 17 ‘17
ИСПОЛЬЗОВАНИЕ
ПАМЯТИ
В MAGENTO 2
© 2017 Magento, Inc. Page | 18 ‘17
СИСТЕМА ИНЪЕКЦИИ ЗАВИСИМОСТЕЙ
public function __construct(
MagentoFrameworkModelContext $context,
MagentoFrameworkRegistry $registry,
MagentoFrameworkStdlibDateTimeTimezoneInterface $localeDate,
MagentoFrameworkViewDesignInterface $design,
MagentoFrameworkModelResourceModelAbstractResource $resource = null,
MagentoFrameworkDataCollectionAbstractDb $resourceCollection = null,
array $data = []
) {
$this->_localeDate = $localeDate;
$this->_design = $design;
parent::__construct($context, $registry, $resource, $resourceCollection,
$data);
}
© 2017 Magento, Inc. Page | 19 ‘17
ПЛАГИНЫ:
AROUND VS BEFORE + AFTER
© 2017 Magento, Inc. Page | 20 ‘17
ПЛАГИНЫ: AROUND
VS BEFORE + AFTER
© 2017 Magento, Inc. Page | 21 ‘17
$collection->setPageSize(1000);
$pages = $collection->getLastPageNumber();
for ($i = 1; $i <= $pages; $i++) {
$collection->resetData();
$collection->setCurPage($i);
$items = $collection->getData();
/** @var MagentoQuoteModelQuote $item */
foreach ($items as $customerItem) {
$guests[] = $this->prepareGuestCustomerModel($customerItem);
}
$collection->clear();
}
ОБРАБОТКА ДАННЫХ “ПАЧКАМИ”
© 2017 Magento, Inc. Page | 22 ‘17
public function deleteIndex($dimensions, Traversable $documents)
{
foreach ($this->batch->getItems($documents, $this->batchSize) as $batchDocuments)
{
$this->resource->getConnection()->delete($this->getTableName($dimensions),
['entity_id in (?)' => $batchDocuments]);
}
}
public function getItems(Traversable $documents, $size){
$i = 0; $batch = [];
foreach ($documents as $documentName => $documentValue) {
$batch[$documentName] = $documentValue;
if (++$i == $size) {
yield $batch;
$i = 0;
$batch = []; }
}
if (count($batch) > 0) {
yield $batch;
}}
© 2017 Magento, Inc. Page | 23 ‘17
ОЧИСТКА КОЛЛЕКЦИИ
$collection->setPageSize(1000);
$pages = $collection->getLastPageNumber();
for ($i = 1; $i <= $pages; $i++) {
$collection->resetData();
$collection->setCurPage($i);
$items = $collection->getData();
/** @var MagentoQuoteModelQuote $item */
foreach ($items as $customerItem) {
$guests[] = $this->prepareGuestCustomerModel($customerItem);
}
$collection->clear();
}
© 2017 Magento, Inc. Page | 24 ‘17
ЭКОНОМНАЯ ЗАГРУЗКА КОЛЛЕКЦИИ
protected function _prepareCollection()
{
$collection = $this->_collectionFactory
->getReport('sales_order_grid_data_source')
->addFieldToSelect('entity_id')
->addFieldToSelect('increment_id')
->addFieldToSelect('customer_id')
->addFieldToSelect('created_at')
->addFieldToSelect('grand_total')
->addFieldToSelect('order_currency_code');
...
© 2017 Magento, Inc. Page | 25 ‘17
private function getApplicableAttributeCodes(array $documentIds){
$attributeSetIds = $this->attributeSetFinder
->findAttributeSetIdsByProductIds($documentIds);
$this->attributeCollection->getSelect()
->reset(MagentoFrameworkDBSelect::COLUMNS)
->columns('attribute_code');
return $this->attributeCollection->getConnection()
->fetchCol($this->attributeCollection->getSelect());
}
ЭКОНОМНАЯ ЗАГРУЗКА КОЛЛЕКЦИИ
© 2017 Magento, Inc. Page | 26 ‘17
КЕШИРОВАНИЕ МЕТОДОВ
private function getUrlModifier() {
if ($this->urlModifier === null) {
$this->urlModifier = MagentoFrameworkAppObjectManager::
getInstance()->get(MagentoFrameworkUrlModifierInterface::class);
}
return $this->urlModifier;
}
© 2017 Magento, Inc. Page | 27 ‘17
© 2017 Magento, Inc. Page | 28 ‘17
ИСПОЛЬЗОВАНИЕ FLAT СТРУКТУРЫ
© 2017 Magento, Inc. Page | 29 ‘17
МАССИВЫ VS МОДЕЛИ
$collection->getData() $collection->getItems()
ЛЕГКО ТЯЖЕЛО
© 2017 Magento, Inc. Page | 30 ‘17
СПАСИБО!

Más contenido relacionado

Similar a Способы оптимизации работы с памятью в Magento 2

Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency Injection
Anton Kril
 

Similar a Способы оптимизации работы с памятью в Magento 2 (20)

Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
Not the WordPress Way
Not the WordPress WayNot the WordPress Way
Not the WordPress Way
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
 
Multi tenant laravel
Multi tenant laravelMulti tenant laravel
Multi tenant laravel
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
 
以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角
 
WordPress Theme Design and Development Workshop - Day 3
WordPress Theme Design and Development Workshop - Day 3WordPress Theme Design and Development Workshop - Day 3
WordPress Theme Design and Development Workshop - Day 3
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
 
Curso Symfony - Clase 2
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency Injection
 
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
GlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScriptGlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScript
 
Building Scalable Websites with Perl
Building Scalable Websites with PerlBuilding Scalable Websites with Perl
Building Scalable Websites with Perl
 

Más de Amasty

Más de Amasty (20)

Magento Security from Developer's and Tester's Points of View
Magento Security from Developer's and Tester's Points of ViewMagento Security from Developer's and Tester's Points of View
Magento Security from Developer's and Tester's Points of View
 
A joyful shopping experience. Creating e-commerce sites that are effortless t...
A joyful shopping experience. Creating e-commerce sites that are effortless t...A joyful shopping experience. Creating e-commerce sites that are effortless t...
A joyful shopping experience. Creating e-commerce sites that are effortless t...
 
Follow up email_for_magento_2_user_guide
Follow up email_for_magento_2_user_guideFollow up email_for_magento_2_user_guide
Follow up email_for_magento_2_user_guide
 
Order Status for Magrnto 2 by Amasty
Order Status for Magrnto 2 by AmastyOrder Status for Magrnto 2 by Amasty
Order Status for Magrnto 2 by Amasty
 
Order Attributes for Magento 2
Order Attributes for Magento 2Order Attributes for Magento 2
Order Attributes for Magento 2
 
Shipping Table Rates for Magento 2 by Amasty | User Guide
Shipping Table Rates for Magento 2 by Amasty | User GuideShipping Table Rates for Magento 2 by Amasty | User Guide
Shipping Table Rates for Magento 2 by Amasty | User Guide
 
Customer Group Catalog for Magento 2. User Guide
Customer Group Catalog for Magento 2. User GuideCustomer Group Catalog for Magento 2. User Guide
Customer Group Catalog for Magento 2. User Guide
 
Product Parts Finder for Magento 2 | User Guide
Product Parts Finder for Magento 2 | User GuideProduct Parts Finder for Magento 2 | User Guide
Product Parts Finder for Magento 2 | User Guide
 
Edit Lock Magento Extension by Amasty | User Guide
Edit Lock Magento Extension by Amasty | User GuideEdit Lock Magento Extension by Amasty | User Guide
Edit Lock Magento Extension by Amasty | User Guide
 
Advanced Reports Magento Extension by Amasty | User Guide
Advanced Reports Magento Extension by Amasty | User GuideAdvanced Reports Magento Extension by Amasty | User Guide
Advanced Reports Magento Extension by Amasty | User Guide
 
A/B Testing Magento Extension by Amasty | User Guide
A/B Testing Magento Extension by Amasty | User GuideA/B Testing Magento Extension by Amasty | User Guide
A/B Testing Magento Extension by Amasty | User Guide
 
Meet Magento Belarus 2015: Andrey Tataranovich
Meet Magento Belarus 2015: Andrey TataranovichMeet Magento Belarus 2015: Andrey Tataranovich
Meet Magento Belarus 2015: Andrey Tataranovich
 
Meet Magento Belarus 2015: Igor Bondarenko
Meet Magento Belarus 2015: Igor BondarenkoMeet Magento Belarus 2015: Igor Bondarenko
Meet Magento Belarus 2015: Igor Bondarenko
 
Meet Magento Belarus 2015: Kristina Pototskaya
Meet Magento Belarus 2015: Kristina PototskayaMeet Magento Belarus 2015: Kristina Pototskaya
Meet Magento Belarus 2015: Kristina Pototskaya
 
Meet Magento Belarus 2015: Mladen Ristić
Meet Magento Belarus 2015: Mladen RistićMeet Magento Belarus 2015: Mladen Ristić
Meet Magento Belarus 2015: Mladen Ristić
 
Meet Magento Belarus 2015: Uladzimir Kalashnikau
Meet Magento Belarus 2015: Uladzimir KalashnikauMeet Magento Belarus 2015: Uladzimir Kalashnikau
Meet Magento Belarus 2015: Uladzimir Kalashnikau
 
Meet Magento Belarus 2015: Jurģis Lukss
Meet Magento Belarus 2015: Jurģis LukssMeet Magento Belarus 2015: Jurģis Lukss
Meet Magento Belarus 2015: Jurģis Lukss
 
Meet Magento Belarus 2015: Sergey Lysak
Meet Magento Belarus 2015: Sergey LysakMeet Magento Belarus 2015: Sergey Lysak
Meet Magento Belarus 2015: Sergey Lysak
 
Meet Magento Belarus 2015: Denis Bosak
Meet Magento Belarus 2015: Denis BosakMeet Magento Belarus 2015: Denis Bosak
Meet Magento Belarus 2015: Denis Bosak
 
Store Credit Magento Extension by Amasty | User Guide
Store Credit Magento Extension by Amasty | User GuideStore Credit Magento Extension by Amasty | User Guide
Store Credit Magento Extension by Amasty | User Guide
 

Último

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
Victor Rentea
 
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
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

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
 
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...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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
 
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...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
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
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Способы оптимизации работы с памятью в Magento 2

  • 1. © 2017 Magento, Inc. Page | 1 ‘17 СПОСОБЫ ОПТИМИЗАЦИИ И РАБОТА С ПАМЯТЬЮ В MAGENTO 2
  • 2. © 2017 Magento, Inc. Page | 2 ‘17 Разработчики в компании «Amasty» Обуховский Евгений Харлап Станислав
  • 3. © 2017 Magento, Inc. Page | 3 ‘17 ИСПОЛЬЗОВАНИЕ ПАМЯТИ В PHP
  • 4. © 2017 Magento, Inc. Page | 4 ‘17
  • 5. © 2017 Magento, Inc. Page | 5 ‘17 ПИКОВОЕ ЗНАЧЕНИЕ ИСПОЛЬЗУЕМОЙ ПАМЯТИ В КБ тестовое веб-приложение с запросами к БД
  • 6. © 2017 Magento, Inc. Page | 6 ‘17 ПАМЯТЬ И МАССИВЫ <?php $startMemory = memory_get_usage(); $array = range(1, 100000); echo memory_get_usage() - $startMemory, ' bytes';
  • 7. © 2017 Magento, Inc. Page | 7 ‘17 ОЧЕВИДНЫЙ ОТВЕТ 800 000 байт Около 780 Кб
  • 8. © 2017 Magento, Inc. Page | 8 ‘17 4,00 Мб ПРАВИЛЬНЫЙ ОТВЕТ В 5 раз больше ожидаемого результата
  • 9. © 2017 Magento, Inc. Page | 9 ‘17 СТРУКТУРА ЭЛЕМЕНТА МАССИВА typedef struct _Bucket { zend_ulong h; zend_string *key; zval val; } Bucket;
  • 10. © 2017 Magento, Inc. Page | 10 ‘17 struct _zval_struct { zend_value value; union { struct { ... } v; uint32_t type_info; } u1; union u2; }; typedef union _zend_value { zend_long lval; double dval; zend_refcounted *counted; zend_string *str; zend_array *arr; zend_object *obj; zend_resource *res; zend_reference *ref; zend_ast_ref *ast; zval *zv; void *ptr; zend_class_entry *ce; zend_function *func; struct { ... } ww; } zend_value; СТРУКТУРА ЭЛЕМЕНТА МАССИВА
  • 11. © 2017 Magento, Inc. Page | 11 ‘17 ХРАНЕНИЕ МАССИВА. ИТОГИ. х64 х32 PHP 7 42 байт * 100 000 30 байт * 100 000 ИТОГ 4 Мб 3 Мб PHP 5.6 или меньше 144 байт * 100 000 76 байт * 100 000 ИТОГ 14 Мб 7.4 Мб
  • 12. © 2017 Magento, Inc. Page | 12 ‘17 UNSET VS ПРИРАВНИВАНИЕ К NULL function memoryUsage($usage, $base_memory_usage) { printf("Bytes diff: %dn", $usage - $base_memory_usage); } $baseUsage = memory_get_usage(); $a = someBigValue(); unset($a); memoryUsage(memory_get_usage(), $baseUsage); $baseUsage = memory_get_usage(); $a = someBigValue(); $a = null; memoryUsage(memory_get_usage(), $baseUsage); Bytes diff: 0 Bytes diff: 76
  • 13. © 2017 Magento, Inc. Page | 13 ‘17 <?php $startMemoryUsage = memory_get_usage(); $bigValue = str_repeat('BIG-BIG STRINGGGGGGGG',1024); $a = array($bigValue, $bigValue, $bigValue, $bigValue); foreach ($a as $k => $v) { $a[$k] = $bigValue; unset($k, $v); Printf("Bytes: %dn", memory_get_usage() – $startMemoryUsage); } echo 'After Foreach.' . PHP_EOL; Printf("Bytes: %dn", memory_get_usage() – $startMemoryUsage); ?> ПЕРЕДАЧА МАССИВОВ ПО ССЫЛКЕ Before Foreach Bytes: 61940 Bytes: 77632 Bytes: 93032 Bytes: 108432 Bytes: 123832 After Foreach Bytes: 61940
  • 14. © 2017 Magento, Inc. Page | 14 ‘17 foreach ($a as $k => &$v) { $a[$k] = $bigValue; unset($k, $v); Printf("Bytes: %dn", memory_get_usage() - $startMemoryUsage); } ПЕРЕДАЧА МАССИВОВ ПО ССЫЛКЕ Bytes: 61940 Bytes: 61940 Bytes: 61940 Bytes: 61940 AFTER FOREACH BYTES: 61940
  • 15. © 2017 Magento, Inc. Page | 15 ‘17
  • 16. © 2017 Magento, Inc. Page | 16 ‘17 SPL FIXED ARRAY <?php $startMemory = memory_get_usage(); $array = new SplFixedArray(100000); for ($i = 0; $i < 100000; ++$i) { $array[$i] = $i; } Достигается тем, что SplFixedArray не нуждается в bucket структуре, только один zval и один указатель для каждого элемента.
  • 17. © 2017 Magento, Inc. Page | 17 ‘17 ИСПОЛЬЗОВАНИЕ ПАМЯТИ В MAGENTO 2
  • 18. © 2017 Magento, Inc. Page | 18 ‘17 СИСТЕМА ИНЪЕКЦИИ ЗАВИСИМОСТЕЙ public function __construct( MagentoFrameworkModelContext $context, MagentoFrameworkRegistry $registry, MagentoFrameworkStdlibDateTimeTimezoneInterface $localeDate, MagentoFrameworkViewDesignInterface $design, MagentoFrameworkModelResourceModelAbstractResource $resource = null, MagentoFrameworkDataCollectionAbstractDb $resourceCollection = null, array $data = [] ) { $this->_localeDate = $localeDate; $this->_design = $design; parent::__construct($context, $registry, $resource, $resourceCollection, $data); }
  • 19. © 2017 Magento, Inc. Page | 19 ‘17 ПЛАГИНЫ: AROUND VS BEFORE + AFTER
  • 20. © 2017 Magento, Inc. Page | 20 ‘17 ПЛАГИНЫ: AROUND VS BEFORE + AFTER
  • 21. © 2017 Magento, Inc. Page | 21 ‘17 $collection->setPageSize(1000); $pages = $collection->getLastPageNumber(); for ($i = 1; $i <= $pages; $i++) { $collection->resetData(); $collection->setCurPage($i); $items = $collection->getData(); /** @var MagentoQuoteModelQuote $item */ foreach ($items as $customerItem) { $guests[] = $this->prepareGuestCustomerModel($customerItem); } $collection->clear(); } ОБРАБОТКА ДАННЫХ “ПАЧКАМИ”
  • 22. © 2017 Magento, Inc. Page | 22 ‘17 public function deleteIndex($dimensions, Traversable $documents) { foreach ($this->batch->getItems($documents, $this->batchSize) as $batchDocuments) { $this->resource->getConnection()->delete($this->getTableName($dimensions), ['entity_id in (?)' => $batchDocuments]); } } public function getItems(Traversable $documents, $size){ $i = 0; $batch = []; foreach ($documents as $documentName => $documentValue) { $batch[$documentName] = $documentValue; if (++$i == $size) { yield $batch; $i = 0; $batch = []; } } if (count($batch) > 0) { yield $batch; }}
  • 23. © 2017 Magento, Inc. Page | 23 ‘17 ОЧИСТКА КОЛЛЕКЦИИ $collection->setPageSize(1000); $pages = $collection->getLastPageNumber(); for ($i = 1; $i <= $pages; $i++) { $collection->resetData(); $collection->setCurPage($i); $items = $collection->getData(); /** @var MagentoQuoteModelQuote $item */ foreach ($items as $customerItem) { $guests[] = $this->prepareGuestCustomerModel($customerItem); } $collection->clear(); }
  • 24. © 2017 Magento, Inc. Page | 24 ‘17 ЭКОНОМНАЯ ЗАГРУЗКА КОЛЛЕКЦИИ protected function _prepareCollection() { $collection = $this->_collectionFactory ->getReport('sales_order_grid_data_source') ->addFieldToSelect('entity_id') ->addFieldToSelect('increment_id') ->addFieldToSelect('customer_id') ->addFieldToSelect('created_at') ->addFieldToSelect('grand_total') ->addFieldToSelect('order_currency_code'); ...
  • 25. © 2017 Magento, Inc. Page | 25 ‘17 private function getApplicableAttributeCodes(array $documentIds){ $attributeSetIds = $this->attributeSetFinder ->findAttributeSetIdsByProductIds($documentIds); $this->attributeCollection->getSelect() ->reset(MagentoFrameworkDBSelect::COLUMNS) ->columns('attribute_code'); return $this->attributeCollection->getConnection() ->fetchCol($this->attributeCollection->getSelect()); } ЭКОНОМНАЯ ЗАГРУЗКА КОЛЛЕКЦИИ
  • 26. © 2017 Magento, Inc. Page | 26 ‘17 КЕШИРОВАНИЕ МЕТОДОВ private function getUrlModifier() { if ($this->urlModifier === null) { $this->urlModifier = MagentoFrameworkAppObjectManager:: getInstance()->get(MagentoFrameworkUrlModifierInterface::class); } return $this->urlModifier; }
  • 27. © 2017 Magento, Inc. Page | 27 ‘17
  • 28. © 2017 Magento, Inc. Page | 28 ‘17 ИСПОЛЬЗОВАНИЕ FLAT СТРУКТУРЫ
  • 29. © 2017 Magento, Inc. Page | 29 ‘17 МАССИВЫ VS МОДЕЛИ $collection->getData() $collection->getItems() ЛЕГКО ТЯЖЕЛО
  • 30. © 2017 Magento, Inc. Page | 30 ‘17 СПАСИБО!