SlideShare a Scribd company logo
© 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
СПАСИБО!

More Related Content

Similar to Способы оптимизации работы с памятью в 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 Framework
Dirk 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 #2
Shinya Ohyanagi
 
Not the WordPress Way
Not the WordPress WayNot the WordPress Way
Not the WordPress Way
Dustin Hartzler
 
Bag Of Tricks From Iusethis
Bag Of Tricks From IusethisBag Of Tricks From Iusethis
Bag Of Tricks From Iusethis
Marcus Ramberg
 
Multi tenant laravel
Multi tenant laravelMulti tenant laravel
Multi tenant laravel
Peter Mein
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
Dzmitry Ivashutsin
 
Bubbles & Trees with jQuery
Bubbles & Trees with jQueryBubbles & Trees with jQuery
Bubbles & Trees with jQuery
Bastian 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 3
Mizanur Rahaman Mizan
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
Konstantin Kudryashov
 
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 2
Javier Eguiluz
 
mongodb-introduction
mongodb-introductionmongodb-introduction
mongodb-introduction
Tse-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 2
Atwix
 
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
Divante
 
GlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScriptGlueCon 2016 - Threading in JavaScript
GlueCon 2016 - Threading in JavaScript
Jonathan Baker
 
Building Scalable Websites with Perl
Building Scalable Websites with PerlBuilding Scalable Websites with Perl
Building Scalable Websites with Perl
Perrin Harkins
 

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

More from 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 View
Amasty
 
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_guide
Amasty
 
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
Amasty
 
Order Attributes for Magento 2
Order Attributes for Magento 2Order Attributes for Magento 2
Order Attributes for Magento 2
Amasty
 
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
Amasty
 
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
Amasty
 
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
Amasty
 
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
Amasty
 
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
Amasty
 
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
Amasty
 
Meet Magento Belarus 2015: Andrey Tataranovich
Meet Magento Belarus 2015: Andrey TataranovichMeet Magento Belarus 2015: Andrey Tataranovich
Meet Magento Belarus 2015: Andrey Tataranovich
Amasty
 
Meet Magento Belarus 2015: Igor Bondarenko
Meet Magento Belarus 2015: Igor BondarenkoMeet Magento Belarus 2015: Igor Bondarenko
Meet Magento Belarus 2015: Igor Bondarenko
Amasty
 
Meet Magento Belarus 2015: Kristina Pototskaya
Meet Magento Belarus 2015: Kristina PototskayaMeet Magento Belarus 2015: Kristina Pototskaya
Meet Magento Belarus 2015: Kristina Pototskaya
Amasty
 
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 Kalashnikau
Amasty
 
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
Amasty
 
Meet Magento Belarus 2015: Sergey Lysak
Meet Magento Belarus 2015: Sergey LysakMeet Magento Belarus 2015: Sergey Lysak
Meet Magento Belarus 2015: Sergey Lysak
Amasty
 
Meet Magento Belarus 2015: Denis Bosak
Meet Magento Belarus 2015: Denis BosakMeet Magento Belarus 2015: Denis Bosak
Meet Magento Belarus 2015: Denis Bosak
Amasty
 
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
Amasty
 

More from 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
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 

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