SlideShare a Scribd company logo
C++ Optimization TipsAbdelrahman Al-Ogail05-12-2010
AgendaHello WorldDoes it deserve?Initialization listTemporariesMemory poolingInlining
Hello WorldWhat we mean by “fast”?When to think about optimization?What to optimize?Fast path.
Does it deserve?//******************* VERSION 0 *******************\\voidMyFunc(){ string x = “1234568” ;}void main(){// Start timing here  for (int i = 0; i < 1000000; i++)  {MyFunc();  } // Stop timing here}
Does it deserve?//******************* VERSION 1 *******************\\voidMyFunc(){char* x = “1234568” ;}void main(){// Start timing here  for (int i = 0; i < 1000000; i++)  {MyFunc();  } // Stop timing here}
Does it deserve?
Initialization list//******************* VERSION 0 *******************\\classMyClass{public:MyClass(strings1, string s2, string s3) {_s1 = s1; _s2 = s2; _s3 = s3; }private:string _s1, _s2, _s3;};void main(){// Start timing here  for (int i = 0; i < 1000000; i++)  {MyClassinstance("123456", "123456", "123456"); } // Stop timing here}
Initialization list//******************* VERSION 1 *******************\\classMyClass{public:MyClass(strings1, string s2, string s3) : _s1(s1), _s2(s2), _s3(s3){}private:string _s1, _s2, _s3;};void main(){// Start timing here  for (int i = 0; i < 1000000; i++)  {MyClassinstance("123456", "123456", "123456"); } // Stop timing here}
Initialization list
Temporaries//******************* VERSION 0 *******************\\void main(){// Start timing here  for (int i = 0; i < 1000000; i++)  {    string s1, s2, s3, s4, s5;   s1 = s2 + s3 + s4 + s5; } // Stop timing here}
Temporaries//******************* VERSION 1 *******************\\void main(){// Start timing here  for (int i = 0; i < 1000000; i++)  {    string s1, s2, s3, s4, s5;   s1 = s2;   s1 += s3;   s1 += s4;   s1 += s5; } // Stop timing here}
Temporaries
Memory PoolingSize of memory to allocate:Static.Dynamic.Environment:Single Threaded.Multi-Threaded.
Quote of Wisdom“Special circumstances allow for simplifying assumptions that in turn, provide opportunities for significant optimizations”
Memory Poolingvoid main(){   MyMemoryManager<MyClass> memManager;  memManager.Reserve(10);   MyClass* instance = memManager.Alloc();// Some code goes here…   // Deallocate the allocated instancememMnagaer.DeAlloc(instance);   // Some code goes here…memManager.Free();}
Memory Pooling
InliningWhy Inlining?Removes method invocation overhead.Let compiler able to optimize code.Why Not Inlining:Code expansion (page fault, exe image size).Linkage problems.Code recompilation.
InliningSome of method invocation overhead*:Passing method parametersCreative stack frame for new callBranching (IP)Passing return values.* architecture depended.
InliningWhat to inline:SingletonsTrivial methodsFast path most frequent method calls.
Inlining – Conditional Inlingx.hx.inlx.cpp#if !defined(_X_H_)#define_X_H_classX{...inty (inta );...};#ifdefined(INLINE)#includex.inl#endif#endif// _X_H_#if !defined(INLINE)#defineinline#endifinlineintX::y (inta){	...}#if !defined(INLINE)#includex.inl#endif
Inlining – Selective InlingFile: x.inl:inlineintx::inline_y (inta){	... // original implementation of y}File: x.h:classx {public: //assuming the original method "y" had public visibility	---intinline_y (inta);inty (inta); // this should already have been here	---};#include"x.inl"// this may already have been here alsoFile: x.c:intx::y (inta){returninline_y(a);}
Thanks!

More Related Content

PPTX
Os Practical Assignment 1
PPTX
Azure Durable Funkiness - .NET Oxford June 2018
PDF
Parallel Computing with R
PDF
Cannot observe ingress packets
PDF
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
KEY
Cocos2d実践編 1.0.0rc
PPTX
Linux kernel debugging
PDF
Алексей Кутумов, Coroutines everywhere
Os Practical Assignment 1
Azure Durable Funkiness - .NET Oxford June 2018
Parallel Computing with R
Cannot observe ingress packets
Rust: код может быть одновременно безопасным и быстрым, Степан Кольцов
Cocos2d実践編 1.0.0rc
Linux kernel debugging
Алексей Кутумов, Coroutines everywhere

What's hot (20)

PDF
Node day 2014
PPT
Евгений Крутько, Многопоточные вычисления, современный подход.
PDF
20140531 serebryany lecture01_fantastic_cpp_bugs
PDF
20140531 serebryany lecture02_find_scary_cpp_bugs
KEY
Lock? We don't need no stinkin' locks!
PPTX
Memory management in cocos2d x - Le Duy Vu
PPT
Full-Stack JavaScript with Node.js
DOCX
Mango64 u boot 업데이트 하기
PDF
Профилирование и оптимизация производительности Ruby-кода
PPTX
The State of JavaScript
PDF
The Ring programming language version 1.5.4 book - Part 54 of 185
PPTX
Code vectorization for mobile devices
DOCX
PDF
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
PDF
OpenGL Starter L02
PPTX
Developing 2D Games with Stage3D
PDF
NS2: AWK and GNUplot - PArt III
PDF
SFO15-500: VIXL
PDF
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
DOCX
Oops pramming with examples
Node day 2014
Евгений Крутько, Многопоточные вычисления, современный подход.
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
Lock? We don't need no stinkin' locks!
Memory management in cocos2d x - Le Duy Vu
Full-Stack JavaScript with Node.js
Mango64 u boot 업데이트 하기
Профилирование и оптимизация производительности Ruby-кода
The State of JavaScript
The Ring programming language version 1.5.4 book - Part 54 of 185
Code vectorization for mobile devices
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
OpenGL Starter L02
Developing 2D Games with Stage3D
NS2: AWK and GNUplot - PArt III
SFO15-500: VIXL
Timur Shemsedinov "Пишу на колбеках, а что... (Асинхронное программирование)"
Oops pramming with examples
Ad

Viewers also liked (18)

PPTX
IoT
PPTX
Android Code Optimization Techniques 3
PPTX
Android Code Optimization Techniques 2
PPTX
Profile Guided Optimization
PPTX
Android Code Optimization Techniques
PDF
Compiler optimization
PDF
Abdelrahman Al-Ogail Resume
PPTX
Improved Teaching Leaning Based Optimization Algorithm
PDF
BKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
PDF
Code Optimization
PPT
Gc in android
PDF
JVM JIT compilation overview by Vladimir Ivanov
PDF
LAS16-201: ART JIT in Android N
PDF
Understanding the Dalvik bytecode with the Dedexer tool
PPTX
optimizing code in compilers using parallel genetic algorithm
PPTX
JEEConf 2016. Effectiveness and code optimization in Java applications
PPTX
Google ART (Android RunTime)
PDF
IoT Smart Home & Connected Car Convergence Insights from Patents
IoT
Android Code Optimization Techniques 3
Android Code Optimization Techniques 2
Profile Guided Optimization
Android Code Optimization Techniques
Compiler optimization
Abdelrahman Al-Ogail Resume
Improved Teaching Leaning Based Optimization Algorithm
BKK16-302: Android Optimizing Compiler: New Member Assimilation Guide
Code Optimization
Gc in android
JVM JIT compilation overview by Vladimir Ivanov
LAS16-201: ART JIT in Android N
Understanding the Dalvik bytecode with the Dedexer tool
optimizing code in compilers using parallel genetic algorithm
JEEConf 2016. Effectiveness and code optimization in Java applications
Google ART (Android RunTime)
IoT Smart Home & Connected Car Convergence Insights from Patents
Ad

Similar to C++ Optimization Tips (20)

PDF
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
PPTX
IOT Firmware: Best Pratices
PPT
Microkernel Development
PPTX
C vs Java: Finding Prime Numbers
PPTX
Node.js System: The Landing
PPTX
DOCX
Implementing of classical synchronization problem by using semaphores
PDF
Actor Concurrency
PDF
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
PPT
Effecient javascript
PPTX
semaphre and condition variable in Operating system
PDF
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
PDF
GPU Programming on CPU - Using C++AMP
PDF
Fault tolerance made easy
DOCX
Assignment
PDF
Node.js Event Loop & EventEmitter
DOCX
Lab 2 Histrogram generation Author Naga Kandasamy .docx
PDF
start_printf: dev/ic/com.c comstart()
PDF
Orasta500.c
PPTX
Decoding Kotlin - Your guide to solving the mysterious in Kotlin - JNation2025
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
IOT Firmware: Best Pratices
Microkernel Development
C vs Java: Finding Prime Numbers
Node.js System: The Landing
Implementing of classical synchronization problem by using semaphores
Actor Concurrency
M.TECH 1ST SEM COMPUTER SCIENCE AOS LAB PRGMS 2014
Effecient javascript
semaphre and condition variable in Operating system
[嵌入式系統] MCS-51 實驗 - 使用 IAR (2)
GPU Programming on CPU - Using C++AMP
Fault tolerance made easy
Assignment
Node.js Event Loop & EventEmitter
Lab 2 Histrogram generation Author Naga Kandasamy .docx
start_printf: dev/ic/com.c comstart()
Orasta500.c
Decoding Kotlin - Your guide to solving the mysterious in Kotlin - JNation2025

More from Abdelrahman Al-Ogail (8)

PPTX
Introduction to C++ Remote Procedure Call (RPC)
PPTX
Introduction to Remote Procedure Call
PPTX
Second Seminar Presentation
PPTX
Case Based Planner Platform For Rts Games
PPTX
Timeline Presentation
PPTX
First Seminar Presentation
PPTX
Case Based Planning A Framework For Planning From Experience
PPTX
Introduction To My Graduation Project
Introduction to C++ Remote Procedure Call (RPC)
Introduction to Remote Procedure Call
Second Seminar Presentation
Case Based Planner Platform For Rts Games
Timeline Presentation
First Seminar Presentation
Case Based Planning A Framework For Planning From Experience
Introduction To My Graduation Project

Recently uploaded (20)

PDF
Traveri Digital Marketing Seminar 2025 by Corey and Jessica Perlman
PDF
COST SHEET- Tender and Quotation unit 2.pdf
PDF
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
PDF
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf
PDF
Chapter 5_Foreign Exchange Market in .pdf
DOCX
Euro SEO Services 1st 3 General Updates.docx
PPTX
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
PDF
Unit 1 Cost Accounting - Cost sheet
PPT
340036916-American-Literature-Literary-Period-Overview.ppt
PDF
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
PDF
Business model innovation report 2022.pdf
PPT
Chapter four Project-Preparation material
PDF
Stem Cell Market Report | Trends, Growth & Forecast 2025-2034
PPTX
Probability Distribution, binomial distribution, poisson distribution
PPTX
Belch_12e_PPT_Ch18_Accessible_university.pptx
PPTX
New Microsoft PowerPoint Presentation - Copy.pptx
PDF
Types of control:Qualitative vs Quantitative
PDF
Dr. Enrique Segura Ense Group - A Self-Made Entrepreneur And Executive
PPT
Data mining for business intelligence ch04 sharda
PDF
WRN_Investor_Presentation_August 2025.pdf
Traveri Digital Marketing Seminar 2025 by Corey and Jessica Perlman
COST SHEET- Tender and Quotation unit 2.pdf
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf
Chapter 5_Foreign Exchange Market in .pdf
Euro SEO Services 1st 3 General Updates.docx
job Avenue by vinith.pptxvnbvnvnvbnvbnbmnbmbh
Unit 1 Cost Accounting - Cost sheet
340036916-American-Literature-Literary-Period-Overview.ppt
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
Business model innovation report 2022.pdf
Chapter four Project-Preparation material
Stem Cell Market Report | Trends, Growth & Forecast 2025-2034
Probability Distribution, binomial distribution, poisson distribution
Belch_12e_PPT_Ch18_Accessible_university.pptx
New Microsoft PowerPoint Presentation - Copy.pptx
Types of control:Qualitative vs Quantitative
Dr. Enrique Segura Ense Group - A Self-Made Entrepreneur And Executive
Data mining for business intelligence ch04 sharda
WRN_Investor_Presentation_August 2025.pdf

C++ Optimization Tips

  • 2. AgendaHello WorldDoes it deserve?Initialization listTemporariesMemory poolingInlining
  • 3. Hello WorldWhat we mean by “fast”?When to think about optimization?What to optimize?Fast path.
  • 4. Does it deserve?//******************* VERSION 0 *******************\\voidMyFunc(){ string x = “1234568” ;}void main(){// Start timing here for (int i = 0; i < 1000000; i++) {MyFunc(); } // Stop timing here}
  • 5. Does it deserve?//******************* VERSION 1 *******************\\voidMyFunc(){char* x = “1234568” ;}void main(){// Start timing here for (int i = 0; i < 1000000; i++) {MyFunc(); } // Stop timing here}
  • 7. Initialization list//******************* VERSION 0 *******************\\classMyClass{public:MyClass(strings1, string s2, string s3) {_s1 = s1; _s2 = s2; _s3 = s3; }private:string _s1, _s2, _s3;};void main(){// Start timing here for (int i = 0; i < 1000000; i++) {MyClassinstance("123456", "123456", "123456"); } // Stop timing here}
  • 8. Initialization list//******************* VERSION 1 *******************\\classMyClass{public:MyClass(strings1, string s2, string s3) : _s1(s1), _s2(s2), _s3(s3){}private:string _s1, _s2, _s3;};void main(){// Start timing here for (int i = 0; i < 1000000; i++) {MyClassinstance("123456", "123456", "123456"); } // Stop timing here}
  • 10. Temporaries//******************* VERSION 0 *******************\\void main(){// Start timing here for (int i = 0; i < 1000000; i++) { string s1, s2, s3, s4, s5; s1 = s2 + s3 + s4 + s5; } // Stop timing here}
  • 11. Temporaries//******************* VERSION 1 *******************\\void main(){// Start timing here for (int i = 0; i < 1000000; i++) { string s1, s2, s3, s4, s5; s1 = s2; s1 += s3; s1 += s4; s1 += s5; } // Stop timing here}
  • 13. Memory PoolingSize of memory to allocate:Static.Dynamic.Environment:Single Threaded.Multi-Threaded.
  • 14. Quote of Wisdom“Special circumstances allow for simplifying assumptions that in turn, provide opportunities for significant optimizations”
  • 15. Memory Poolingvoid main(){ MyMemoryManager<MyClass> memManager; memManager.Reserve(10); MyClass* instance = memManager.Alloc();// Some code goes here… // Deallocate the allocated instancememMnagaer.DeAlloc(instance); // Some code goes here…memManager.Free();}
  • 17. InliningWhy Inlining?Removes method invocation overhead.Let compiler able to optimize code.Why Not Inlining:Code expansion (page fault, exe image size).Linkage problems.Code recompilation.
  • 18. InliningSome of method invocation overhead*:Passing method parametersCreative stack frame for new callBranching (IP)Passing return values.* architecture depended.
  • 19. InliningWhat to inline:SingletonsTrivial methodsFast path most frequent method calls.
  • 20. Inlining – Conditional Inlingx.hx.inlx.cpp#if !defined(_X_H_)#define_X_H_classX{...inty (inta );...};#ifdefined(INLINE)#includex.inl#endif#endif// _X_H_#if !defined(INLINE)#defineinline#endifinlineintX::y (inta){ ...}#if !defined(INLINE)#includex.inl#endif
  • 21. Inlining – Selective InlingFile: x.inl:inlineintx::inline_y (inta){ ... // original implementation of y}File: x.h:classx {public: //assuming the original method "y" had public visibility ---intinline_y (inta);inty (inta); // this should already have been here ---};#include"x.inl"// this may already have been here alsoFile: x.c:intx::y (inta){returninline_y(a);}