SlideShare a Scribd company logo
1 of 25
Tail-call Optimization
(TCO)
What is tail-call optimization?
A compiler optimization that allows

the efficient use of procedure calls in
the tail position
What’s a procedure?
Blocks of callable code
 Functions

 Methods
 Subroutines

 Routines
What does it mean for a procedure
call to be in tail position?
A procedure call is in tail position if it’s
the last thing to happen before

returning
int a = bar():
return a + 1;
}

Example 1

public static void foo1(){
int a = bar():
return a;
}

Example 2

public static void foo2(){
Where does the inefficiency
come from?
Call stack
Container for storing procedure calls
Grows upward
Last in, first out (LIFO)
Composed of stack frames
Keeping with current analogies…
 Each pancake represents some procedure to be
stepped through (some computation).
 The plate represents boilerplate used by the runtime
system to return from procedures once they’ve run to
completion.
 Boilerplate might consist of return addresses, formal
parameters, etc.
What’s in a stack frame?
Each stack frame is made of up of:
 Some computation to run (a pancake)
 Some boilerplate used for returning (a plate)

So our stack really looks more like this…
Specifically…

↵

b()
a()
main()
Fine-tuning the analogy…
Remember, we consider a pancake
some amount of computation/work that
needs to be performed before a
procedure can return.
So we would expect the pancake to
vary in size over the course of its lifetime.
Concretely…

;

b()
a()
↵
main()
What would the stack look like if
our functions made use of tail
calls?
Probably something like this…

b()

↵

a()
main()
So where’s the inefficiency?
Oh no, stack overflow!
Our stack has to exist in memory, so
it has a finite size.

If we have too many stack frames,
eventually we’ll run out of room
and get a stack overflow.
A solution approaches
 If procedure calls are in tail position, we can
pop their remaining stack frame, since the
plate is all that’s left.

 Since stack frames aren’t something the
programmer deals with explicitly, we let the
compiler take care of the details.
 Thus we have tail call elimination/optimization.
(TCE/TCO)
A comparison
Without TCO

With TCO

b()
a()

main()

b()
main()
Why should I care about this?
Benefits of TCO
You can solve problems efficiently using
recursion.

You can make efficient use of function
calls within procedures.
More stack space means more room for
the procedures that aren’t able to make
use of tail calls.
More examples:
https://gist.github.com/numberten/4acb8e7e8988caba8b5d
Related Wikipedia pages
 http://en.wikipedia.org/wiki/Call_stack
 http://en.wikipedia.org/wiki/Tail_call
 http://en.wikipedia.org/wiki/Subroutines
 http://en.wikipedia.org/wiki/Mutual_recursion
 http://en.wikipedia.org/wiki/Structured_programming

More Related Content

What's hot

A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink Jaewook. Kang
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Peng Cheng
 
190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pubJaewook. Kang
 
Taming OpenBSD Network Stack Dragons by Martin Pieuchot
Taming OpenBSD Network Stack Dragons by Martin PieuchotTaming OpenBSD Network Stack Dragons by Martin Pieuchot
Taming OpenBSD Network Stack Dragons by Martin Pieuchoteurobsdcon
 
Tensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi chaTensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi chaDonghwi Cha
 
なぜ検索しなかったのか
なぜ検索しなかったのかなぜ検索しなかったのか
なぜ検索しなかったのかN Masahiro
 
An evaluation of LLVM compiler for SVE with fairly complicated loops
An evaluation of LLVM compiler for SVE with fairly complicated loopsAn evaluation of LLVM compiler for SVE with fairly complicated loops
An evaluation of LLVM compiler for SVE with fairly complicated loopsLinaro
 
Arm tools and roadmap for SVE compiler support
Arm tools and roadmap for SVE compiler supportArm tools and roadmap for SVE compiler support
Arm tools and roadmap for SVE compiler supportLinaro
 
GEM - GNU C Compiler Extensions Framework
GEM - GNU C Compiler Extensions FrameworkGEM - GNU C Compiler Extensions Framework
GEM - GNU C Compiler Extensions FrameworkAlexey Smirnov
 
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...Yusuke Izawa
 
Two-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One EngineTwo-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One EngineYusuke Izawa
 

What's hot (20)

A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink
 
Ch7
Ch7Ch7
Ch7
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
Shape Safety in Tensor Programming is Easy for a Theorem Prover -SBTB 2021
 
190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub
 
The low level awesomeness of Go
The low level awesomeness of GoThe low level awesomeness of Go
The low level awesomeness of Go
 
Taming OpenBSD Network Stack Dragons by Martin Pieuchot
Taming OpenBSD Network Stack Dragons by Martin PieuchotTaming OpenBSD Network Stack Dragons by Martin Pieuchot
Taming OpenBSD Network Stack Dragons by Martin Pieuchot
 
Concurrency in Python4k
Concurrency in Python4kConcurrency in Python4k
Concurrency in Python4k
 
project_2
project_2project_2
project_2
 
Recursion
RecursionRecursion
Recursion
 
Tensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi chaTensorflow in practice by Engineer - donghwi cha
Tensorflow in practice by Engineer - donghwi cha
 
なぜ検索しなかったのか
なぜ検索しなかったのかなぜ検索しなかったのか
なぜ検索しなかったのか
 
An evaluation of LLVM compiler for SVE with fairly complicated loops
An evaluation of LLVM compiler for SVE with fairly complicated loopsAn evaluation of LLVM compiler for SVE with fairly complicated loops
An evaluation of LLVM compiler for SVE with fairly complicated loops
 
Run time
Run timeRun time
Run time
 
Arm tools and roadmap for SVE compiler support
Arm tools and roadmap for SVE compiler supportArm tools and roadmap for SVE compiler support
Arm tools and roadmap for SVE compiler support
 
GEM - GNU C Compiler Extensions Framework
GEM - GNU C Compiler Extensions FrameworkGEM - GNU C Compiler Extensions Framework
GEM - GNU C Compiler Extensions Framework
 
Parallel Programming
Parallel ProgrammingParallel Programming
Parallel Programming
 
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...
Stack Hybridization: A Mechanism for Bridging Two Compilation Strategies in a...
 
Two-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One EngineTwo-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One Engine
 
Return Oriented Programming
Return Oriented ProgrammingReturn Oriented Programming
Return Oriented Programming
 

Similar to Tail call optimization (TCO) - Lecture

Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCAFxX
 
Compiler optimization
Compiler optimizationCompiler optimization
Compiler optimizationZongYing Lyu
 
May2010 hex-core-opt
May2010 hex-core-optMay2010 hex-core-opt
May2010 hex-core-optJeff Larkin
 
Handling Large State on BEAM
Handling Large State on BEAMHandling Large State on BEAM
Handling Large State on BEAMYoshihiro TANAKA
 
Making our Future better
Making our Future betterMaking our Future better
Making our Future betterlegendofklang
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in goborderj
 
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFunction Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFaisal Shehzad
 
CJPCCS BCA VISNAGAR functions in C language
CJPCCS BCA VISNAGAR  functions in C languageCJPCCS BCA VISNAGAR  functions in C language
CJPCCS BCA VISNAGAR functions in C languageFCSCJCS
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
 
Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...
Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...
Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...Intel® Software
 
Low Level Exploits
Low Level ExploitsLow Level Exploits
Low Level Exploitshughpearse
 

Similar to Tail call optimization (TCO) - Lecture (20)

Compiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flatteningCompiler optimizations based on call-graph flattening
Compiler optimizations based on call-graph flattening
 
Compiler optimization
Compiler optimizationCompiler optimization
Compiler optimization
 
May2010 hex-core-opt
May2010 hex-core-optMay2010 hex-core-opt
May2010 hex-core-opt
 
Handling Large State on BEAM
Handling Large State on BEAMHandling Large State on BEAM
Handling Large State on BEAM
 
Buffer overflow attack
Buffer overflow attackBuffer overflow attack
Buffer overflow attack
 
Operating System Engineering
Operating System EngineeringOperating System Engineering
Operating System Engineering
 
test
testtest
test
 
Making our Future better
Making our Future betterMaking our Future better
Making our Future better
 
Concurrency in go
Concurrency in goConcurrency in go
Concurrency in go
 
Savitch ch 04
Savitch ch 04Savitch ch 04
Savitch ch 04
 
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal ShahzadFunction Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
Function Overloading,Inline Function and Recursion in C++ By Faisal Shahzad
 
2.0 Stacks.pptx
2.0 Stacks.pptx2.0 Stacks.pptx
2.0 Stacks.pptx
 
Savitch Ch 04
Savitch Ch 04Savitch Ch 04
Savitch Ch 04
 
Savitch Ch 04
Savitch Ch 04Savitch Ch 04
Savitch Ch 04
 
CJPCCS BCA VISNAGAR functions in C language
CJPCCS BCA VISNAGAR  functions in C languageCJPCCS BCA VISNAGAR  functions in C language
CJPCCS BCA VISNAGAR functions in C language
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...
Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...
Fast Insights to Optimized Vectorization and Memory Using Cache-aware Rooflin...
 
Low Level Exploits
Low Level ExploitsLow Level Exploits
Low Level Exploits
 
Code optimization
Code optimizationCode optimization
Code optimization
 
Code optimization
Code optimizationCode optimization
Code optimization
 

Recently uploaded

Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxDr.Ibrahim Hassaan
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Gas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptxGas measurement O2,Co2,& ph) 04/2024.pptx
Gas measurement O2,Co2,& ph) 04/2024.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 

Tail call optimization (TCO) - Lecture

  • 2. What is tail-call optimization? A compiler optimization that allows the efficient use of procedure calls in the tail position
  • 3. What’s a procedure? Blocks of callable code  Functions  Methods  Subroutines  Routines
  • 4. What does it mean for a procedure call to be in tail position? A procedure call is in tail position if it’s the last thing to happen before returning
  • 5. int a = bar(): return a + 1; } Example 1 public static void foo1(){
  • 6. int a = bar(): return a; } Example 2 public static void foo2(){
  • 7. Where does the inefficiency come from?
  • 8. Call stack Container for storing procedure calls Grows upward Last in, first out (LIFO) Composed of stack frames
  • 9.
  • 10. Keeping with current analogies…  Each pancake represents some procedure to be stepped through (some computation).  The plate represents boilerplate used by the runtime system to return from procedures once they’ve run to completion.  Boilerplate might consist of return addresses, formal parameters, etc.
  • 11. What’s in a stack frame? Each stack frame is made of up of:  Some computation to run (a pancake)  Some boilerplate used for returning (a plate) So our stack really looks more like this…
  • 12.
  • 14. Fine-tuning the analogy… Remember, we consider a pancake some amount of computation/work that needs to be performed before a procedure can return. So we would expect the pancake to vary in size over the course of its lifetime.
  • 16. What would the stack look like if our functions made use of tail calls?
  • 17. Probably something like this… b() ↵ a() main()
  • 18. So where’s the inefficiency?
  • 19. Oh no, stack overflow! Our stack has to exist in memory, so it has a finite size. If we have too many stack frames, eventually we’ll run out of room and get a stack overflow.
  • 20. A solution approaches  If procedure calls are in tail position, we can pop their remaining stack frame, since the plate is all that’s left.  Since stack frames aren’t something the programmer deals with explicitly, we let the compiler take care of the details.  Thus we have tail call elimination/optimization. (TCE/TCO)
  • 21. A comparison Without TCO With TCO b() a() main() b() main()
  • 22. Why should I care about this?
  • 23. Benefits of TCO You can solve problems efficiently using recursion. You can make efficient use of function calls within procedures. More stack space means more room for the procedures that aren’t able to make use of tail calls.
  • 25. Related Wikipedia pages  http://en.wikipedia.org/wiki/Call_stack  http://en.wikipedia.org/wiki/Tail_call  http://en.wikipedia.org/wiki/Subroutines  http://en.wikipedia.org/wiki/Mutual_recursion  http://en.wikipedia.org/wiki/Structured_programming