Implementing Faster Defers

Implementing Faster Defers

Gopher Academy via YouTube Direct link

Intro

1 of 12

1 of 12

Intro

Class Central Classrooms beta

YouTube playlists curated by Class Central.

Classroom Contents

Implementing Faster Defers

Automatically move to the next video in the Classroom when playback concludes

  1. 1 Intro
  2. 2 Defer Statement • defer keyword followed by a function or method call The function pointer and arguments are evaluated immediately, but the call is deferred until the current function finishes • The …
  3. 3 Defer Performance Goal Goal for defer optimization in Go 1.14 • Make defor overhead low enough that programmers can use defer in any function whenever it is helpful • End the common belief that defer…
  4. 4 Related language constructs • RAll (Resource Acquisition is Initialization) - C++
  5. 5 Advantages of Defer • Improves maintainability: guarantees cleanup will happen even if more function exits are added • Improves robustness: guarantees cleanup will happen even if there is a panic - e…
  6. 6 Implementing Go's Defer • Defer is completely dynamic (can be called inside a loop, conditional etc.) • A straightforward implementation must be handled by the Go runtime, in order to deal with the d…
  7. 7 Defer chain • Linked list of currently active defer records Each defer record contains function pointer, defer args, pointer to stack frame Each defer record may be on stack or heap (if defer is in a…
  8. 8 Defer chain & panics • runtime gopanic processes defer records in LIFO order as well: Calls the appropriate function with the defer args Continues until all defer records are processed, or one of the
  9. 9 Idea: make deferred calls directly in simple cases . Only applicable for functions where no defer statement is in a loop • At defer statements, compiler generates code to evaluate and store into stac…
  10. 10 Compiler notes for open-coded defers • We must ensure that the defer arguments are stored to their stack slots (not just kept in registers), so they are available in case of panic • Similarly, update…
  11. 11 Panic processing for open-coded defers • How to handle panics - we don't have a defer record any more... • Record in funcdata all the information about each defer, including stack slots where the fun…
  12. 12 Future optimizations • Eliminate deferBits check for any unconditional defer (even when other defers are conditional) • Use constant arguments directly in the defer calls at exit • Do inlining of def…

Never Stop Learning.

Get personalized course recommendations, track subjects and courses with reminders, and more.

Someone learning on their laptop while sitting on the floor.