SlideShare une entreprise Scribd logo
1  sur  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
СПАСИБО!

Contenu connexe

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

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 FrameworkDirk Haun
 
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 JasminePaulo Ragonha
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Shinya Ohyanagi
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From IusethisMarcus Ramberg
 
Multi tenant laravel
Multi tenant laravelMulti tenant laravel
Multi tenant laravelPeter Mein
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQueryBastian Feder
 
以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角以Vue開發電子商務網站
架構與眉角
以Vue開發電子商務網站
架構與眉角Mei-yu Chen
 
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 3Mizanur Rahaman Mizan
 
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'...Ben Teese
 
Curso Symfony - Clase 2
Curso Symfony - Clase 2Curso Symfony - Clase 2
Curso Symfony - Clase 2Javier Eguiluz
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introductionTse-Ching Ho
 
Magento Dependency Injection
Magento Dependency InjectionMagento Dependency Injection
Magento Dependency InjectionAnton Kril
 
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2
Сергей Иващенко - Meet Magento Ukraine - Цены в Magento 2Atwix
 
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 scenariosDivante
 
GlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScriptGlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScriptJonathan Baker
 
Building Scalable Websites with Perl
Building Scalable Websites with PerlBuilding Scalable Websites with Perl
Building Scalable Websites with PerlPerrin Harkins
 

Similaire à Способы оптимизации работы с памятью в 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
 

Plus de Amasty

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 ViewAmasty
 
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...Amasty
 
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_guideAmasty
 
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 AmastyAmasty
 
Order Attributes for Magento 2
Order Attributes for Magento 2Order Attributes for Magento 2
Order Attributes for Magento 2Amasty
 
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 GuideAmasty
 
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 GuideAmasty
 
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 GuideAmasty
 
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 GuideAmasty
 
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 GuideAmasty
 
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 GuideAmasty
 
Meet Magento Belarus 2015: Andrey Tataranovich
Meet Magento Belarus 2015: Andrey TataranovichMeet Magento Belarus 2015: Andrey Tataranovich
Meet Magento Belarus 2015: Andrey TataranovichAmasty
 
Meet Magento Belarus 2015: Igor Bondarenko
Meet Magento Belarus 2015: Igor BondarenkoMeet Magento Belarus 2015: Igor Bondarenko
Meet Magento Belarus 2015: Igor BondarenkoAmasty
 
Meet Magento Belarus 2015: Kristina Pototskaya
Meet Magento Belarus 2015: Kristina PototskayaMeet Magento Belarus 2015: Kristina Pototskaya
Meet Magento Belarus 2015: Kristina PototskayaAmasty
 
Meet Magento Belarus 2015: Mladen Ristić
Meet Magento Belarus 2015: Mladen RistićMeet Magento Belarus 2015: Mladen Ristić
Meet Magento Belarus 2015: Mladen RistićAmasty
 
Meet Magento Belarus 2015: Uladzimir Kalashnikau
Meet Magento Belarus 2015: Uladzimir KalashnikauMeet Magento Belarus 2015: Uladzimir Kalashnikau
Meet Magento Belarus 2015: Uladzimir KalashnikauAmasty
 
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 LukssAmasty
 
Meet Magento Belarus 2015: Sergey Lysak
Meet Magento Belarus 2015: Sergey LysakMeet Magento Belarus 2015: Sergey Lysak
Meet Magento Belarus 2015: Sergey LysakAmasty
 
Meet Magento Belarus 2015: Denis Bosak
Meet Magento Belarus 2015: Denis BosakMeet Magento Belarus 2015: Denis Bosak
Meet Magento Belarus 2015: Denis BosakAmasty
 
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 GuideAmasty
 

Plus 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
 

Dernier

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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, Adobeapidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Dernier (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

Способы оптимизации работы с памятью в 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 СПАСИБО!