Minimising memory churn

Slides:



Advertisements
Similar presentations
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Advertisements

Topic 10 Java Memory Management. 1-2 Memory Allocation in Java When a program is being executed, separate areas of memory are allocated for each class.
C# Language Report By Trevor Adams. Language History Developed by Microsoft Developed by Microsoft Principal Software Architect Principal Software Architect.
Language Fundamentals in brief C# - Introduction.
CSC321: Programming Languages 11-1 Programming Languages Tucker and Noonan Chapter 11: Memory Management 11.1 The Heap 11.2 Implementation of Dynamic Arrays.
Reference Types. 2 Objectives Introduce reference types –class –array Discuss details of use –declaration –allocation –assignment –null –parameter –aggregation.
FEN 2012 UCN Technology: Computer Science1 C# - Introduction Language Fundamentals in Brief.
References types and Value types With a very brief introduction to struct and enum Reference types and Value types1.
1 Names, Scopes and Bindings Aaron Bloomfield CS 415 Fall
Stack and Heap Memory Stack resident variables include:
1 Object Oriented Programming Lecture IX Some notes on Java Performance with aspects on execution time and memory consumption.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
C++ Memory Overview 4 major memory segments Key differences from Java
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
1 9/6/05CS360 Windows Programming CS360 Windows Programming.
Introduction to C# By: Abir Ghattas Michel Barakat.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
Learners Support Publications Constructors and Destructors.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Memory Management.
Constructors and Destructors
CIS199 Test Review 2 REACH.
Garbage Collection What is garbage and how can we deal with it?
Dynamic Storage Allocation
Run-Time Environments Chapter 7
Learning Objectives Pointers as dada members
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
Test 2 Review Outline.
Overview 4 major memory segments Key differences from Java stack
Arrays Low level collections.
Lecture 2 Memory management.
Computing with C# and the .NET Framework
FUNCTIONS AND PARAMETERS
Advanced Programming Behnam Hatami Fall 2017.
C# In many ways, C# looks similar to Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Object Based Programming
Chapter 6 Arrays Solution Opening Problem
Overview 4 major memory segments Key differences from Java stack
understanding memory usage by a c++ program
Contents Introduction to Constructor Characteristics of Constructor
Overview of Memory Layout in C++
Pointers, Dynamic Data, and Reference Types
Introducing Arrays Array is a data structure that represents a collection of the same types of data.
Constructors and Destructors
CLEANING UP UNUSED OBJECTS
Assessment – Java Basics: Part 1
By Andrew Horn And Ryan Kluck
9-10 Classes: A Deeper Look.
Dynamic Memory.
Applet Fundamentals Applet are small applications that are accessed on an Internet server, transported over the Internet, automatically installed and run.
C H A P T E R F I V E Memory Management.
Lecture 2 Memory management.
Pointers, Dynamic Data, and Reference Types
9-10 Classes: A Deeper Look.
Classes and Objects Object Creation
Corresponds with Chapter 5
Storage classes in C In C language, each variable has a storage class which decides the following things: scope i.e where the value of the variable would.
Garbage Collection What is garbage and how can we deal with it?
Interfaces, Enumerations, Boxing, and Unboxing
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Minimising memory churn With examples in C# by Christopher Myburgh Technical Director at Team Devil Games www.teamdevil.com

stack memory & heap memory Objects are always destroyed in the opposite order that they are created. Every thread has its own stack. Heap Objects have an indeterminate lifetime. In managed environments, a “garbage collector” must periodically run to free memory from unreferenced objects. The heap becomes fragmented as objects are destroyed. A severely fragmented heap might cause allocations to take longer.

“mark-and-sweep” garbage collector basics Traverses the object graph starting from static variables and the stack(s). Tags all the heap objects it encounters. All heap objects that remain untagged when traversal is completed are then destroyed, and the memory that they occupied is made available for re-use.

Memory churn Is the rate of creation and destruction of objects in heap memory. The higher the churn, the more severely the heap could become fragmented, the more often the garbage collector might be triggered and the more work the garbage collector may have to do. A tell-tale sign of severe memory churn in games is small but regular pauses in gameplay, caused by the garbage collector running very frequently and taking exceedingly long to complete (1 or more entire frames). Severe memory churn is caused by repeatedly creating heap objects with very short lifetimes.

Best practices to minimise memory churn Avoid creating heap objects inside loops that are forgotten at the end of each iteration. class Foo { void DoSomething() // ... } void DoStuff(int count) { for (int i = 0; i < count; ++i) // allocated within the loop Foo myHeapObject = new Foo(); myHeapObject.DoSomething(); } void DoStuff(int count) { // allocated outside the loop Foo myHeapObject = new Foo(); for (int i = 0; i < count; ++i) myHeapObject.DoSomething(); }

Best practices to minimise memory churn Avoid creating heap objects during every update that are forgotten at the end of the update. class Foo { void DoSomething() // ... } class MyScript { void Update() // allocated during the update Foo myHeapObject = new Foo(); myHeapObject.DoSomething(); } class MyScript { // allocated before any updates Foo myHeapObject = new Foo(); void Update() myHeapObject.DoSomething(); }

Best practices to minimise memory churn Pool game objects that occur frequently (eg. projectiles in a shoot-em-up). class Projectile { void Enable() // ... } void Disable() class ProjectileManager { Queue<Projectile> projectilePool = new Queue<Projectile>(); Projectile CreateProjectile() Projectile projectile; // Get an unused projectile from the pool, // or create a new one if there are none spare. if (projectilePool.Count > 0) projectile = projectilePool.Dequeue(); else projectile = new Projectile(); projectile.Enable(); return projectile; } void DestroyProjectile(Projectile projectile) // Return the unused projectile to the pool. projectile.Disable(); projectilePool.Enqueue(projectile);

reference types & value types in C# Objects are always allocated on the heap. Include classes, interfaces, arrays and delegates. Value types Objects are allocated on the stack when declared as local variables or as method parameters, or form part of the object on the heap when declared as class members or as the element type of an array. Include enums and structs.

Implicit heap allocations in C# string concatenation class Player { public string Name; public int Score; } // ... // ToString() is called on player.Score and concatenations generate new strings string hudText = "Name: " + player.Name + "; Score = " + player.Score; boxing int num = 0; object numObj = num; // creates a copy of num on the heap interface IMyInterface { // … } struct MyStruct : IMyInterface { // … } MyStruct myStruct = new MyStruct(); IMyInterface myInterface = myStruct; // creates a copy of myStruct on the heap

Implicit heap allocations in C# delegate creation bool LessThanZero(int x) { return x < 0; } List<int> myList = new List<int>(); // … // The first statement is just shorthand for the second. myList.RemoveAll(LessThanZero); myList.RemoveAll(new Predicate<int>(LessThanZero)); lambda expressions List<int> myList = new List<int>(); // … // A delegate is allocated for an anonymous method. myList.RemoveAll(x => x < 0); // Captured variables are implemented as members of an anonymous class which must also be allocated. int j = 0; myList.RemoveAll(x => x < j);

Implicit heap allocations in C# delegate chaining void DoSomething1() { // … } void DoSomething2() { // … } void DoSomething3() { // … } Action action1 = DoSomething1; Action action2 = DoSomething2; // New delegates are allocated when chained. // By default, events are implemented by chaining delegates. Action actionAll = action1 + action2; actionAll += DoSomething3;

Implicit heap allocations in C# foreach loops (in many but not all cases) foreach (T item in myEnumerableObject) { // … } // The above foreach loop is shorthand for the loop below, so check the return type of GetEnumerator(). // If the return type is a struct, the enumerator is allocated on the stack. // If the return type is a class, the enumerator is allocated on the heap. // If the return type is an interface, either a class is allocated on the heap or a struct is boxed. using (var anonymousEnumerator = myEnumerableObject.GetEnumerator()) { while (anonymousEnumerator.MoveNext()) { T item = (T)anonymousEnumerator.Current; // read-only // … } }

Implicit heap allocations in C# params method arguments int AddAll(params int[] nums) { // … } int num1 = 1, num2 = 2, num3 = 3; int sum; // The first statement is just shorthand for the second. sum = AddAll(num1, num2, num3); sum = AddAll(new int[] { num1, num2, num3 }); passing strings from an unmanaged context to a managed context

'k thanks bye.