C# Memory Tricks: Learn How To Master The Garbage Collector

This course teaches you advanced C# memory management tricks that every professional .NET developer must know.
4.5 (38 ratings)
Instead of using a simple lifetime average, Udemy calculates a
course's star rating by considering a number of different factors
such as the number of ratings, the age of ratings, and the
likelihood of fraudulent ratings.
892 students enrolled
$19
$90
79% off
Take This Course
  • Lectures 28
  • Length 3.5 hours
  • Skill Level All Levels
  • Languages English
  • Includes Lifetime access
    30 day money back guarantee!
    Available on iOS and Android
    Certificate of Completion
Wishlisted Wishlist

How taking a course works

Discover

Find online courses made by experts from around the world.

Learn

Take your courses with you and learn anywhere, anytime.

Master

Learn and practice real-world skills and achieve your goals.

About This Course

Published 9/2015 English

Course Description

BEST COURSE CHOICE for beginners and intermediate C# developers who want to learn how to master the garbage collector and take their programming skills to the next level.

Modern computers have loads of memory. But it's very easy to burn through all of it in a couple of minutes if your code is not efficient about allocating and using memory.

Did you know that one simple mistake can make your code allocate 1600 times more memory than absolutely necessary?

Don't be 'that developer' who keeps crashing the development server with an OutOfMemory exception!

And you certainly don't want to be responsible for inflating the hardware budget. Can you imagine having to explain to your team that 512 GB of memory is not enough to run your code on the production server?

Let me help you.

It doesn't have to be like this. If you have a good understanding of the garbage collection process and follow a few simple best practices, you can dramatically reduce the memory footprint of your code.

Sound good?

In the last 10 years I have learned the secrets of garbage collection in .NET, and in this course I am going to share them all with you.

In a series of short lectures I will take a detailed look at the garbage collection process. I will show you all of the memory allocation problems you can expect when writing C# code, like unexpected boxing, string duplication, collection resizing, and more. I'll teach you quick and easy strategies to resolve these problems.

By the end of this course you will be able to master the garbage collector.

Why should you take this course?

You should take this course if you are a beginner or intermediate C# developer and want to take your skills to the next level. Garbage collection and memory management might sound complicated, but all of my lectures are very easy to follow and I explain all topics with clear code and many instructive diagrams. You'll have no trouble following along.

Or maybe you're working on a critical section of code in a C# project, and need to make sure your memory usage is as efficient as possible? The tips and tricks in this course will help you immensely.

Or maybe you're preparing for a C# related job interview? This course will give you an excellent foundation to answer any questions they might throw at you.

30 day money-back guarantee

This course comes with an unconditional, Udemy backed, 30-day money-back guarantee. If you are dissatisfied with the course for any reason, simply request a refund and get your full purchase amount back, no questions asked.

Act now

This course today contains over 3 hours of video content and I am adding new material every month. Enrol now to benefit from the current price and get free lifelong access to all future materials.

Enrol now!

What are the requirements?

  • You should have a Windows, Mac or Linux laptop with Microsoft Visual Studio, Xamarin Studio or Monodevelop installed
  • You should be familiar with the C# language
  • That's all!

What am I going to get from this course?

  • Learn how to write efficient C# code from a certified Microsoft trainer from your own desk.
  • Many hours of video content teaching you about garbage collection, finalisers, memory optimisation, and much more!
  • Suitable for beginner and intermediate programmers and ideal for users who learn faster when shown.
  • Learn the secrets of Garbage Collection.
  • What are the risks of using finalisers?
  • Structs versus classes - which one is better?
  • See how lists and collections sometimes use 4x more memory than neccessary.

What is the target audience?

  • This course is for beginner and intermediate C# programmers who want to learn how to master the garbage collector.
  • Ideal for students who are about to take a job interview, and need to prepare for questions about memory allocation in .NET
  • Are you writing a section of code in a large C# project, and need to be sure it will run efficiently in production? Then this course is for you!

What you get with this course?

Not for you? No problem.
30 day money back guarantee.

Forever yours.
Lifetime access.

Learn on the go.
Desktop, iOS and Android.

Get rewarded.
Certificate of completion.

Curriculum

Section 1: Introduction
04:12

In this lecture I explain how this course is organised and I describe each of the upcoming sections in detail.

03:50

In this lecture I will tell a bit more about myself, my career, and my motivation to become an online trainer.

04:17

In this lecture we're going to look at the theory behind .NET memory management. What exactly is Garbage Collection, and how does it work?

03:19

Many lectures in this course contain source code examples. Feel free to download the code and follow along. And here's the good news: it doesn't matter if you have a Window, Mac or Linux computer. The code will run on all three operating systems.

In this lecture I demonstrate how my solutions and projects run on all operating systems. I will show you how to build and run the source code on a Mac, on Linux and in Visual Studio running on Windows 8.

At the end of this lecture you will have learned that .NET code is portable and can run on at least five different operating systems.

Section 2: Fundamentals Of The .NET Framework
00:43

Welcome to the Fundamentals of .NET Memory Management section. I will give a quick introduction on how the section is organised before we get started.

05:23

This lesson will lay down some groundwork and explain in detail what the stack is for, and how data on the stack is laid out in memory.

After completing this lecture you will have learned which data is stored on the stack and what happens when this data goes out of scope. Finally, you will have seen a Stack Overflow exception, and know how to avoid this exception in your own code.

04:59

This lesson will lay down some groundwork and explain in detail what the heap is for, and how data on the heap is laid out in memory.

After completing this lecture you will have learned which data is stored on the heap and what happens when variables that refer to this data go out of scope. Finally, you will be able to explain what the 'Garbage collection' process does.

05:42

A popular question that often comes up in job interviews is: "what is the difference between a value type and a reference type?"

This lecture looks at value types in detail. What are value types, how do they store their data, and what happens when value types are assigned or compared? After completing this lecture you will be able to answer all of these questions with ease.

05:29

A popular question that often comes up in job interviews is: "what is the difference between a value type and a reference type?"

This lecture looks at reference types in detail. What are reference types, how do they store their data, and what happens when reference types are assigned or compared? After completing this lecture you will be able to answer all of these questions with ease.

06:04

Value types and reference types are both derived from the same common base class "Object". This is a nice feature of the .NET Framework, but behind the scenes it creates some problems for the runtime environment because reference types can never exist on the stack.

In this lecture you will learn how .NET uses a cool trick called "Boxing" to get around this problem. After completing the lecture you will be able to explain what boxing and unboxing is, and why it is neccesary.

02:55

Congratulations on finishing this section. This is a recap of what we have learned.

Section 3: A Detailed Look At Garbage Collection
01:48

Welcome to the Detailed Look At Garbage Collection section. I will give a quick introduction on how the section is organised before we get started.

16:46

The .NET Garbage Collector is responsible for cleaning up all dereferenced objects on the heap. In this lecture we are going to take a long hard look at its internal architecture.

I will show you how the Garbage Collector uses a mark-and-sweep cycle to periodically clean the heap, how it uses generations to sort objects into short-living and long-living groups, and how it is specifically optimized for handling large objects.

After completing this lecture you will be able to describe in detail how the Garbage Collector works. You will also be aware of the assumptions it makes about object sizes and lifetimes.

18:20

In this lecture we're going to look at a couple of specific performance improvements you can make to your code, that will help you work with the Garbage Collector instead of against it.

We will look in detail at the assumptions the Garbage Collector makes about the size and lifetime of the objects in your code, and how you can take advantage of these assumptions by carefully designing your objects.

After completing this lecture you will have learned how to write fast and efficient code that works in harmony with the Garbage Collector.

17:11

In this lecture we are going to take a closer look at finalisers, which are special methods that are called by the .NET Garbage Collector just before an object gets deallocated. Finalisers offer a very convenient safety net for last-minute deallocation and disposing of resources held by the object.

But finalisers are dangerous and very hard to get right. I will show you three big disadvantages of finalisers in terms of code robustness and memory performance.

16:34

Sometimes an object needs to access scarce operating system resources, like a graphics device handle, a database connection, or a block of unmanaged memory. The Dispose pattern is an efficient design pattern in .NET to quickly release these resources when they are no longer needed.

In his lecture you will learn why the dispose pattern is much more efficient than simply releasing the resources in the finaliser, and I will also teach you how to write a reference implementation of the design pattern.

04:07

Congratulations on finishing this section. This is a recap of what we have learned.

Garbage Collection
10 questions
Section 4: Simple Tricks To Improve Memory Allocation In Your Code
01:19

Welcome to the Simple Tricks section. I will give a quick introduction on how the section is organised before we get started.

11:50

The .NET runtime uses a very cool trick called 'boxing' that allows you to use value types and reference types interchangeably in your code.

In this lecture I will use a test program to measure exact how much overhead the boxing operation introduces. You will see how to use the log profiler built into the Mono framework to track what the garbage collector is doing while the program is running.

After completing this lecture you will have learned why boxing is best avoided in mission-critical code.

16:09

Strings in .NET are immutable. This can introduce a large memory footprint when modifying strings, especially when done in a loop.

In this lecture I'll show you a test program that builds a string of 10,000 characters using either simple string concatenation, or the StringBuilder class. We will investigate exactly how much heap memory is allocated, how often the garbage collector runs, and which methods are called in each scenario.

By the end of the lecture you will have learned why you should always use a StringBuilder to modify strings in mission critical code.

17:55

Structs in C# are Value Types, which means they are allocated inline with other data, either on the stack or on the heap. This can save a lot of memory, especially if you quickly need to allocate millions of items.

In this lecture I will show you a test program that uses structs and classes to store a large amount of data. The struct- and class-based implementations will go head to head to determine which has the smallest memory footprint.

By the end of the lecture you will have learned in which scenarios a struct is the best choice for storing data.

12:30

Collections and lists in .NET automatically resize their internal buffer to accommodate the addition of new items. This is a very nice feature because it means you never have to worry about the size of your lists.

But successive resizes can litter the heap with dereferenced storage buffers and inflate the memory footprint of your code. I will demonstrate a program that fills a list with items and ends up allocating much more memory than it actually needs.

By the end of this lecture you will have learned a very simple trick to keep the memory allocation of lists and collections firmly under control.

18:04

LINQ is a nice feature of the C# language that lets you access enumerated data with a flexible and powerful query language. LINQ queries can access any data that supports the IEnumerable interface. But thoughtless use of LINQ can produce a large memory overhead and can significantly slow down your code.

In this lecture I will show you a spellchecker that uses LINQ and allocates way too much memory. Then I'll demonstrate a simple change that has a dramatic impact on the memory footprint.

03:52

Congratulations on finishing this section. This is a recap of what we have learned.

Memory Allocation Tricks
10 questions
Section 5: Final Words
01:44

In this lecture I would like to thank you for finishing the course and offer some final words.

Section 6: Bonus Section
02:34

In this bonus lecture I would like to offer you an exclusive discount on another of my courses that teaches you how to radically speed up your C# code.

02:38

In this bonus lecture I would like to offer you an exclusive discount on another of my courses that teaches you how to write robust and "bulletproof" multi-threaded C# code.

02:37

In this bonus lecture I would like to offer you an exclusive discount on another of my courses that teaches you about C# anti-patterns and bad coding practices.

Students Who Viewed This Course Also Viewed

  • Loading
  • Loading
  • Loading

Instructor Biography

Mark Farragher, Microsoft Trainer

Hi I'm Mark, and I am very pleased to meet you!

My IT career spans 2 decades and I've worn many different hats over the years. I am a serial entrepreneur and have launched two startups in The Netherlands. I've also been a CTO three times.

I started working with C# and the .NET framework 15 years ago. Today I live in Barcelona and spend my time creating online courses to share my knowledge of professional C# programming with a wide audience.

Ready to start learning?
Take This Course