SlideShare a Scribd company logo
1 of 61
Download to read offline
C# Tips and Tricks
Francis Duranceau
Lead Field Engineer, Unity
Plan
• The C# compiler
• .NET 4.6
• Marshalling
• Understanding Boxing, Foreach, Stack vs. Heap allocation
• GameManager Singleton pattern
C# compiler
C# compiler
• The VM is an abstract stack machine
• Then, we compile
• Source file goes through
• Tree builder that results into an
• Abstract syntax tree that goes into the
• Attribute evaluator that turns into an
• Attributed tree that then feeds the
• Tree walker that finally generates the
• IL
C# compiler
int SimpleCondition(int input)
{
if(input >= 0)
return input * 2;
else
return -input;
}
C# compiler
<projectDir>/Temp/StagingArea/IL2Cpp/il2cppOutput/Bulk_Assembly-CSharp_*.cpp
.NET 4.6
.NET 4.6
Most notably :
• Async
• Tasks
• DataContracts
• Cryptography
• Networking
.NET 4.6 -> C# 6.0
• Null-Conditional Operator
• Auto-Property Initializers
• Nameof Expressions
• Primary Constructors
• Expression Bodied Functions and Properties
.NET 4.6 -> C# 6.0
After .NET 4.6...
.NET 4.6 FAQ
• What platforms does this affect? All of them, but in different ways:
- Editor and Standalone use the new version of Mono when this option is enabled.
- All console platforms will only be able to use IL2CPP when targeting the new .NET version.
- iOS and WebGL will continue to be IL2CPP only.
- Android will continue to support both Mono and IL2CPP.
- Other platforms are still undergoing work to support either new Mono or IL2CPP
• What about IL2CPP? IL2CPP fully supports the new .NET 4.6 APIs and
features.
.NET 4.6 FAQ
• What about the a new GC?
The newer Mono garbage collector (SGen) requires additional work in Unity
and will follow once we have stabilized the new runtime and class libraries.
• Why are my builds larger with the new .NET version?
The .NET 4.6 class libraries are quite larger than our current .NET 3.5 class
libraries. We are actively working on improving the managed linker to
reduce size further.
Marshalling
What is ‘Unmanaged’ Code?
• As the name implies, unmanaged code means YOU are responsible for
a host of things, that are usually taken care of for you when using
managed code. For example:
• Memory management
• Thread Synchronization
• Security
• Life-time control of objects
• Etc.
Using Unmanaged Code
Access managed through DLL / Libraries
[DllImport (“YourCode”)] followed by a function name, which needs to be
static and extern
Place a plugin directory alongside the ‘Assets’ folder in your project and
place the library there
If you get a “DllNotFoundException” make sure the path is correct and
your library is present in the Plugins directory.
DLL in Unity
Put your plugins in :
• Assets/Plugins
• Assets/Plugins/x86
• Assets/Plugins/x86_64
Once you have create / compiled and place
your DLL / library in the right place, you can
call it directly from your managed code.
Invoking Unmanaged Code
• Generally speaking, you just call the method associated with the DLLImport tag.
• Using GetProcAddress(), the specific function is looked up and executed.
• Unfortunately, things aren’t that simple (surprise!)
• C ABI is used for most calls.
• Makes it near impossible to call functions that don’t adhere to this, like C++.
• Again, ABI’s are platform specific.
• Use either __stdcall and __cdecl for VC++ or __attribute__((stdcall)) and
• __attribute__((cdecl)) for GCC.
• If you need to invoke C++ code, use ‘extern “C”’ to ensure the calling convention is adhered to.
Exceptions
• Runtime Exceptions can happen and unmanaged code needs to be able
to deal with it.
• Unfortunately, C doesn’t support exceptions
• C++ does to some extent but has a different mechanism.
• Don’t cross the streams and let exceptions propagate between
managed and unmanaged code or you run the risk of things going bad
Marshalling
• Marshalling is the process of ‘converting’ parameters from managed to
unmanaged space.
• For simple types, this just becomes a straight copy (byte, int, floats,
etc)
• Sometimes called ‘blitting’
• Bool, Strings, Arrays are a little more complex….
• Depends on what type of string it is:
• Ascii, UTF-8, UTF-16, etc.
• Memory boundaries need to be kept separate!
• Don’t keep references around to managed data!
• Data is usually released after call, with obvious consequences.
• Possible to lock a memory area by using the C# ’fixed’ statement.
• Generally, memory is copied around!
Marshalling (Cnt’d)
• Strings, Classes and Structs
• As mentioned earlier, strings are handled different than blittable data
types.
• CLR doesn’t just look for single function but function based on the
type. I.e. Different functions for different objects passed in.
• In order to facilitate this, you can ‘MarshallAs’ and describe your
own datatype, as follows:
[DllImport (”somedll")]
private static extern void Foo (
[MarshalAs(UnmanagedType.LPStr)] string ansiString,
[MarshalAs(UnmanagedType.LPWStr)] string unicodeString,
[MarshalAs(UnmanagedType.LPTStr)] string platformString
);
Marshalling (Cnt’d)
• Structs and classes can’t be passed by value, only by reference.
• Since it’s managed memory, anything that’s copied may move / change.
• Generally a bad thing to do anyway!
• Structs and classes differ by alignment.
• Structs are sequentially aligned by default (as you’d expect)
• Classes may or may not be laid out in memory the way you defined them!
• If you must have them sequential, use the [StructLayout
(LayoutKind.Sequential)] tag.
• Return values should be copied back into managed memory.
Memory Management / Custom
Marshalling
• Memory managed owned by CLI will be managed by CLI
• I.e. a reference to an object passed down to unmanaged code will be
reclaimed by the CLI.
• Both managed and unmanaged memory allocations come from the
same pool.
• Use Marshall.AllocCoTaskMem() and Marshall.FreeCoTaskMem()
• Rather than having built-in Marshalling, you can use create custom
ones.
• Use ‘MarshalAs’
• Remember that you’ll need to write implementations for all variations
of objects passed in!
Bottom Line
• Don’t overlook the impact Marshalling has on your code.
• You’re copying memory around!
• Make sure you know who owns what. I.e. The CG doesn’t know what
you own / use.
• Unless you have a valid reason for using unmanaged code, stick to
managed code.
Example of marshalling
struct Boss {
char* name;
int health;
};
int SumBossHealth(Boss* bosses, int size) {
int sum = 0;
for (int i = 0; i < size; ++i) {
sum += bosses[i].health;
}
return sum;
}
bool IsBossDead(Boss b) {
return b.health == 0;
}
Example of marshalling
[DllImport("__Internal")]
[return: MarshalAs(UnmanagedType.U1)]
private extern static bool IsBossDead(Boss b);
[DllImport("__Internal")]
private extern static int SumBossHealth(Boss[] bosses, int size);
Example of marshalling
Boss[] bosses = {new Boss("First Boss", 25), new Boss("Second Boss",
45)};
Debug.Log (string.Format ("Marshaling a non-blittable struct: {0}",
IsBossDead (new Boss("Final Boss", 100))));
Debug.Log(string.Format("Marshaling an array by reference: {0}",
SumBossHealth (bosses, bosses.Length)));
Best practices
UnderstandingBoxing, Foreach,Stack vs. Heap allocation
Best practices - Boxing
using UnityEngine;
using System.Collections;
public class InputAxis : MonoBehaviour
{
void Update ()
{
float x = Input.GetAxis("Horizontal");
Debug.Log(x);
}
Best practices
extern "C" void InputAxis_Update_m397189571 (InputAxis_t277341211 * __this, const
MethodInfo* method) {
[...]
float V_0 = 0.0f;
{
IL2CPP_RUNTIME_CLASS_INIT(Input_t1785128008_il2cpp_TypeInfo_var);
float L_0 = Input_GetAxis_m2098048324(NULL /*static, unused*/,
_stringLiteral855845486, /*hidden argument*/NULL);
V_0 = L_0; float L_1 = V_0; float L_2 = L_1;
Il2CppObject * L_3 = Box(Single_t2076509932_il2cpp_TypeInfo_var, &L_2);
IL2CPP_RUNTIME_CLASS_INIT(Debug_t1368543263_il2cpp_TypeInfo_var);
Debug_Log_m920475918(NULL /*static, unused*/, L_3, /*hidden argument*/NULL);
return;
}
}
Best practices - Foreach
int ForEachArray (int[] items)
{
var total = 0;
foreach (var item in items)
total += item;
return total;
}
Best practices - Foreach
int ForEachArray(int[] items)
{
int num = 0;
for (int i = 0; i < items.Length; i++)
{
int num2 = items[i];
num += num2;
}
return num;
}
Best practices – Foreach on collections
To avoid allocations when using foreach over a collection the following criteria need to be
met:
- For collections of value types, the collection and enumerator implement the generic interfaces
IEnumerable<T> and IEnumerator<T>.
- The enumerator implementation is a struct not a class.
- The collection has a public method named GetEnumerator whose return type is the enumerator
struct.
The BCL types System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<T>, and
System.Collections.Generic.HashSet<T> all follow the guidelines above and should be safe to
perform foreach statements on.
Best practices – Foreach on collections
int ForEachCustom (CustomCollection items)
{
var total = 0;
foreach (int item in items)
total += item;
return total;
}
Specify the type explicitely -> public class Enumerator : IEnumerator<int>, not just an Enumerator
on Systems.Objects (by default).
Use a struct and not a class so your when you do new in GetEnumerator, it goes on the stack and
not the heap -> return new Enumerator (this);
Best practices – Foreach on collections
class CustomCollection : IEnumerable<int>
{
private readonly int[] _items;
public CustomCollection(int[] items) { _items = items; }
public Enumerator GetEnumerator ()
{ return new Enumerator (this); }
IEnumerator<int> IEnumerable<int>.GetEnumerator ()
{ return GetEnumerator (); }
IEnumerator IEnumerable.GetEnumerator ()
{ return GetEnumerator (); }
public struct Enumerator : IEnumerator<int>
{
private readonly CustomCollection _collection;
private int _index;
[...]
}
}
Best practices
public class ClassVsStruct : MonoBehaviour {
struct PointStruct
{ public int x; public int y; }
class PointClass
{ public int x; public int y; }
void Update()
{
PointStruct ps; ps.x = 3; ps.y = 4;
PointStruct ps2 = new PointStruct(); ps2.x = 7; ps2.y = 8;
PointClass pc = new PointClass(); pc.x = 5; pc.y = 6;
gameObject.transform.position.Set( ps.x + pc.x, ps.y + pc.y, 0);
}
}
.method private hidebysig instance void Update () cil managed
{
.maxstack 4
.locals init (
[0] valuetype ClassVsStruct/PointStruct,
[1] valuetype ClassVsStruct/PointStruct,
[2] class ClassVsStruct/PointClass,
[3] valuetype [UnityEngine]UnityEngine.Vector3 )
IL_0000: ldloca.s 0
IL_0002: ldc.i4.3
IL_0003: stfld int32 ClassVsStruct/PointStruct::x
IL_0008: ldloca.s 0
IL_000a: ldc.i4.4
IL_000b: stfld int32 ClassVsStruct/PointStruct::y
IL_0010: ldloca.s 1
IL_0012: initobj ClassVsStruct/PointStruct
IL_0018: ldloca.s 1
IL_001a: ldc.i4.7
IL_001b: stfld int32 ClassVsStruct/PointStruct::x
IL_0020: ldloca.s 1
IL_0022: ldc.i4.8
IL_0023: stfld int32 ClassVsStruct/PointStruct::y
IL_0028: newobj instance void ClassVsStruct/PointClass::.ctor()
IL_002d: stloc.2
IL_002e: ldloc.2
IL_002f: ldc.i4.5
Best practices
• Strings are immutable and will make copies
• Use String.Builder
• Use a hash to avoid Strings
static readonly int material_Color = Shader.PropertyToID(“_Color”);
static readonly int anim_Attack = Animator.StringToHash(“attack”);
material.SetColor(material_Color, Color.white);
animator.SetTrigger(anim_Attack);
The GC.Collect myth
• There’s a myth saying that when you want to call GC.Collect, you should
do it 6 times.
• Another myth says it’s 7 times.
• Is that really true?
The GC.Collect myth
• On some platforms the GC can decommit memory from virtual memory
• And that happens after so many collections without some pages being
needed
• But it can never be used by anything other than GC because it is still
reserved … that address range is not available for any other allocator in
the process
• tldr; There isn’t much benefits. Unless you do something wrong and want
to be nice to other applications running on that OS.
Best practices
Vector3.zero really does get { return new Vector3(0,0,0); }
GameManager pattern
GameManager pattern
• In this use case, there is a very important lesson to learn. But to show you
the lesson, I will do a very common mistake…
• The Singleton is a very good candidate that can be called thousands of
times per frame
• Let’s look at one way to implement it.
GameManager pattern
GameManager pattern
0.34ms
0.35ms
GameManager pattern
• static bool IsNativeObjectAlive(UnityEngine.Object o)
• {
• #if !UNITY_EDITOR
return o.GetCachedPtr() != IntPtr.Zero;
#else
if (o.GetCachedPtr() != IntPtr.Zero)
return true;
if (o is MonoBehaviour || o is ScriptableObject)
return false;
return DoesObjectWithInstanceIDExist(o.GetInstanceID());
#endif
}
GameManager pattern
using UnityEngine.Profiling;
public class SingletonCaller : MonoBehaviour
{
CustomSampler samplerFind;
[...]
void Start()
{
samplerFind = CustomSampler.Create("CallSingletonGameFind");
}
[...]
void Update()
{
samplerFind.Begin();
CallSingletonGameFind();
samplerFind.End();
}
}
GameManager pattern
Never profile a game running in
the editor.
? operator
string str = null;
void Test1()
{
str?.ToUpper();
}
void Test2()
{
if(str != null)
str.ToUpper();
}
? operator
What about…
• MonoBehaviour vs class?
• Sealed
• Static
• Unsafe
• LINQ
• Generic
Finally…
Conclusion
• Some C# keywords are hiding overhead and allocations
• Prefer POD and struct of classes
• int, float, struct
• NOT class, NOT strings
• Check the resulting IL
• But more importantly than anything else …
Only profile if the profiler tells
you to do so
Thank you!

More Related Content

What's hot

What is jubatus? How it works for you?
What is jubatus? How it works for you?What is jubatus? How it works for you?
What is jubatus? How it works for you?Kumazaki Hiroki
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and FallaciesRoman Elizarov
 
Millions quotes per second in pure java
Millions quotes per second in pure javaMillions quotes per second in pure java
Millions quotes per second in pure javaRoman Elizarov
 
Puppet and CloudStack
Puppet and CloudStackPuppet and CloudStack
Puppet and CloudStackke4qqq
 
Automating CloudStack with Puppet - David Nalley
Automating CloudStack with Puppet - David NalleyAutomating CloudStack with Puppet - David Nalley
Automating CloudStack with Puppet - David NalleyPuppet
 
Using Protocol to Refactor
Using Protocol to Refactor Using Protocol to Refactor
Using Protocol to Refactor Green Chiu
 
Pitfalls of object_oriented_programming_gcap_09
Pitfalls of object_oriented_programming_gcap_09Pitfalls of object_oriented_programming_gcap_09
Pitfalls of object_oriented_programming_gcap_09Royce Lu
 
Infrastructure as code with Puppet and Apache CloudStack
Infrastructure as code with Puppet and Apache CloudStackInfrastructure as code with Puppet and Apache CloudStack
Infrastructure as code with Puppet and Apache CloudStackke4qqq
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPLGyuwon Yi
 
Data oriented design and c++
Data oriented design and c++Data oriented design and c++
Data oriented design and c++Mike Acton
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?Roman Elizarov
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waitingRoman Elizarov
 
Third Party Auth in WebObjects
Third Party Auth in WebObjectsThird Party Auth in WebObjects
Third Party Auth in WebObjectsWO Community
 
Advanced Imaging on iOS
Advanced Imaging on iOSAdvanced Imaging on iOS
Advanced Imaging on iOSrsebbe
 
C++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroC++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroMohammad Shaker
 
EclipseCon 2016 - OCCIware : one Cloud API to rule them all
EclipseCon 2016 - OCCIware : one Cloud API to rule them allEclipseCon 2016 - OCCIware : one Cloud API to rule them all
EclipseCon 2016 - OCCIware : one Cloud API to rule them allMarc Dutoo
 

What's hot (20)

What is jubatus? How it works for you?
What is jubatus? How it works for you?What is jubatus? How it works for you?
What is jubatus? How it works for you?
 
Java Serialization Facts and Fallacies
Java Serialization Facts and FallaciesJava Serialization Facts and Fallacies
Java Serialization Facts and Fallacies
 
Millions quotes per second in pure java
Millions quotes per second in pure javaMillions quotes per second in pure java
Millions quotes per second in pure java
 
Puppet and CloudStack
Puppet and CloudStackPuppet and CloudStack
Puppet and CloudStack
 
Automating CloudStack with Puppet - David Nalley
Automating CloudStack with Puppet - David NalleyAutomating CloudStack with Puppet - David Nalley
Automating CloudStack with Puppet - David Nalley
 
Using Protocol to Refactor
Using Protocol to Refactor Using Protocol to Refactor
Using Protocol to Refactor
 
Pitfalls of object_oriented_programming_gcap_09
Pitfalls of object_oriented_programming_gcap_09Pitfalls of object_oriented_programming_gcap_09
Pitfalls of object_oriented_programming_gcap_09
 
Infrastructure as code with Puppet and Apache CloudStack
Infrastructure as code with Puppet and Apache CloudStackInfrastructure as code with Puppet and Apache CloudStack
Infrastructure as code with Puppet and Apache CloudStack
 
Introduction to TPL
Introduction to TPLIntroduction to TPL
Introduction to TPL
 
Data oriented design and c++
Data oriented design and c++Data oriented design and c++
Data oriented design and c++
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Why GC is eating all my CPU?
Why GC is eating all my CPU?Why GC is eating all my CPU?
Why GC is eating all my CPU?
 
Task and Data Parallelism
Task and Data ParallelismTask and Data Parallelism
Task and Data Parallelism
 
Non blocking programming and waiting
Non blocking programming and waitingNon blocking programming and waiting
Non blocking programming and waiting
 
UI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QMLUI Programming with Qt-Quick and QML
UI Programming with Qt-Quick and QML
 
Eusecwest
EusecwestEusecwest
Eusecwest
 
Third Party Auth in WebObjects
Third Party Auth in WebObjectsThird Party Auth in WebObjects
Third Party Auth in WebObjects
 
Advanced Imaging on iOS
Advanced Imaging on iOSAdvanced Imaging on iOS
Advanced Imaging on iOS
 
C++ Windows Forms L01 - Intro
C++ Windows Forms L01 - IntroC++ Windows Forms L01 - Intro
C++ Windows Forms L01 - Intro
 
EclipseCon 2016 - OCCIware : one Cloud API to rule them all
EclipseCon 2016 - OCCIware : one Cloud API to rule them allEclipseCon 2016 - OCCIware : one Cloud API to rule them all
EclipseCon 2016 - OCCIware : one Cloud API to rule them all
 

Viewers also liked

プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~Takuya Akiba
 
An Internal of LINQ to Objects
An Internal of LINQ to ObjectsAn Internal of LINQ to Objects
An Internal of LINQ to ObjectsYoshifumi Kawai
 
Union find(素集合データ構造)
Union find(素集合データ構造)Union find(素集合データ構造)
Union find(素集合データ構造)AtCoder Inc.
 
深さ優先探索による塗りつぶし
深さ優先探索による塗りつぶし深さ優先探索による塗りつぶし
深さ優先探索による塗りつぶしAtCoder Inc.
 
【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~
【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~
【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~Unity Technologies Japan K.K.
 
【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-
【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-
【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-Unity Technologies Japan K.K.
 

Viewers also liked (6)

プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
プログラミングコンテストでのデータ構造 2 ~平衡二分探索木編~
 
An Internal of LINQ to Objects
An Internal of LINQ to ObjectsAn Internal of LINQ to Objects
An Internal of LINQ to Objects
 
Union find(素集合データ構造)
Union find(素集合データ構造)Union find(素集合データ構造)
Union find(素集合データ構造)
 
深さ優先探索による塗りつぶし
深さ優先探索による塗りつぶし深さ優先探索による塗りつぶし
深さ優先探索による塗りつぶし
 
【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~
【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~
【Unite 2017 Tokyo】Unity最適化講座 ~スペシャリストが教えるメモリとCPU使用率の負担最小化テクニック~
 
【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-
【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-
【Unity道場スペシャル 2017札幌】最適化をする前に覚えておきたい技術 -札幌編-
 

Similar to 【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス

Similar to 【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス (20)

Aspdot
AspdotAspdot
Aspdot
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri0507 057 01 98 * Adana Cukurova Klima Servisleri
0507 057 01 98 * Adana Cukurova Klima Servisleri
 
embedded C.pptx
embedded C.pptxembedded C.pptx
embedded C.pptx
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Exception
ExceptionException
Exception
 
06.1 .Net memory management
06.1 .Net memory management06.1 .Net memory management
06.1 .Net memory management
 
Jvm memory model
Jvm memory modelJvm memory model
Jvm memory model
 
Core java
Core javaCore java
Core java
 
Core java
Core javaCore java
Core java
 
INTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c languageINTRODUCTION TO C PROGRAMMING in basic c language
INTRODUCTION TO C PROGRAMMING in basic c language
 
Intro to .NET and Core C#
Intro to .NET and Core C#Intro to .NET and Core C#
Intro to .NET and Core C#
 
Elixir
ElixirElixir
Elixir
 
Basics of C
Basics of CBasics of C
Basics of C
 
Java SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).pptJava SpringMVC SpringBOOT (Divergent).ppt
Java SpringMVC SpringBOOT (Divergent).ppt
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Linux device drivers
Linux device driversLinux device drivers
Linux device drivers
 
Design Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best PracticesDesign Like a Pro: Scripting Best Practices
Design Like a Pro: Scripting Best Practices
 
Oop c++class(final).ppt
Oop c++class(final).pptOop c++class(final).ppt
Oop c++class(final).ppt
 

More from Unity Technologies Japan K.K.

建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】
建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】
建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】Unity Technologies Japan K.K.
 
UnityのクラッシュをBacktraceでデバッグしよう!
UnityのクラッシュをBacktraceでデバッグしよう!UnityのクラッシュをBacktraceでデバッグしよう!
UnityのクラッシュをBacktraceでデバッグしよう!Unity Technologies Japan K.K.
 
Unityで始めるバーチャルプロダクション
Unityで始めるバーチャルプロダクションUnityで始めるバーチャルプロダクション
Unityで始めるバーチャルプロダクションUnity Technologies Japan K.K.
 
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしようビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしようUnity Technologies Japan K.K.
 
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーション
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーションビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーション
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - UnityステーションUnity Technologies Japan K.K.
 
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそう
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそうビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそう
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそうUnity Technologies Japan K.K.
 
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!Unity Technologies Japan K.K.
 
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】Unity Technologies Japan K.K.
 
Unity教える先生方注目!ティーチャートレーニングデイを体験しよう
Unity教える先生方注目!ティーチャートレーニングデイを体験しようUnity教える先生方注目!ティーチャートレーニングデイを体験しよう
Unity教える先生方注目!ティーチャートレーニングデイを体験しようUnity Technologies Japan K.K.
 
「原神」におけるコンソールプラットフォーム開発
「原神」におけるコンソールプラットフォーム開発「原神」におけるコンソールプラットフォーム開発
「原神」におけるコンソールプラットフォーム開発Unity Technologies Japan K.K.
 
FANTASIANの明日使えない特殊テクニック教えます
FANTASIANの明日使えない特殊テクニック教えますFANTASIANの明日使えない特殊テクニック教えます
FANTASIANの明日使えない特殊テクニック教えますUnity Technologies Japan K.K.
 
インディーゲーム開発の現状と未来 2021
インディーゲーム開発の現状と未来 2021インディーゲーム開発の現状と未来 2021
インディーゲーム開発の現状と未来 2021Unity Technologies Japan K.K.
 
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】Unity Technologies Japan K.K.
 
Burstを使ってSHA-256のハッシュ計算を高速に行う話
Burstを使ってSHA-256のハッシュ計算を高速に行う話Burstを使ってSHA-256のハッシュ計算を高速に行う話
Burstを使ってSHA-256のハッシュ計算を高速に行う話Unity Technologies Japan K.K.
 
Cinemachineで見下ろし視点のカメラを作る
Cinemachineで見下ろし視点のカメラを作るCinemachineで見下ろし視点のカメラを作る
Cinemachineで見下ろし視点のカメラを作るUnity Technologies Japan K.K.
 
Unityティーチャートレーニングデイ -認定プログラマー編-
Unityティーチャートレーニングデイ -認定プログラマー編-Unityティーチャートレーニングデイ -認定プログラマー編-
Unityティーチャートレーニングデイ -認定プログラマー編-Unity Technologies Japan K.K.
 
Unityティーチャートレーニングデイ -認定3Dアーティスト編-
Unityティーチャートレーニングデイ -認定3Dアーティスト編-Unityティーチャートレーニングデイ -認定3Dアーティスト編-
Unityティーチャートレーニングデイ -認定3Dアーティスト編-Unity Technologies Japan K.K.
 
Unityティーチャートレーニングデイ -認定アソシエイト編-
Unityティーチャートレーニングデイ -認定アソシエイト編-Unityティーチャートレーニングデイ -認定アソシエイト編-
Unityティーチャートレーニングデイ -認定アソシエイト編-Unity Technologies Japan K.K.
 

More from Unity Technologies Japan K.K. (20)

建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】
建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】
建築革命、更に更に進化!便利さ向上【Unity Reflect ver 3.0 】
 
UnityのクラッシュをBacktraceでデバッグしよう!
UnityのクラッシュをBacktraceでデバッグしよう!UnityのクラッシュをBacktraceでデバッグしよう!
UnityのクラッシュをBacktraceでデバッグしよう!
 
Unityで始めるバーチャルプロダクション
Unityで始めるバーチャルプロダクションUnityで始めるバーチャルプロダクション
Unityで始めるバーチャルプロダクション
 
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしようビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
ビジュアルスクリプティング (旧:Bolt) で始めるUnity入門3日目 ゲームをカスタマイズしよう
 
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーション
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーションビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーション
ビジュアルスクリプティングで始めるUnity入門2日目 ゴールとスコアの仕組み - Unityステーション
 
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそう
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそうビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそう
ビジュアルスクリプティングで始めるUnity入門1日目 プレイヤーを動かそう
 
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!
PlasticSCMの活用テクニックをハンズオンで一緒に学ぼう!
 
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】
点群を使いこなせ! 可視化なんて当たり前、xRと点群を組み合わせたUnityの世界 【Interact , Stipple】
 
Unity教える先生方注目!ティーチャートレーニングデイを体験しよう
Unity教える先生方注目!ティーチャートレーニングデイを体験しようUnity教える先生方注目!ティーチャートレーニングデイを体験しよう
Unity教える先生方注目!ティーチャートレーニングデイを体験しよう
 
「原神」におけるコンソールプラットフォーム開発
「原神」におけるコンソールプラットフォーム開発「原神」におけるコンソールプラットフォーム開発
「原神」におけるコンソールプラットフォーム開発
 
FANTASIANの明日使えない特殊テクニック教えます
FANTASIANの明日使えない特殊テクニック教えますFANTASIANの明日使えない特殊テクニック教えます
FANTASIANの明日使えない特殊テクニック教えます
 
インディーゲーム開発の現状と未来 2021
インディーゲーム開発の現状と未来 2021インディーゲーム開発の現状と未来 2021
インディーゲーム開発の現状と未来 2021
 
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】
建築革命、更に進化!デジタルツイン基盤の真打ち登場【概要編 Unity Reflect ver 2.1 】
 
Burstを使ってSHA-256のハッシュ計算を高速に行う話
Burstを使ってSHA-256のハッシュ計算を高速に行う話Burstを使ってSHA-256のハッシュ計算を高速に行う話
Burstを使ってSHA-256のハッシュ計算を高速に行う話
 
Cinemachineで見下ろし視点のカメラを作る
Cinemachineで見下ろし視点のカメラを作るCinemachineで見下ろし視点のカメラを作る
Cinemachineで見下ろし視点のカメラを作る
 
徹底解説 Unity Reflect【開発編 ver2.0】
徹底解説 Unity Reflect【開発編 ver2.0】徹底解説 Unity Reflect【開発編 ver2.0】
徹底解説 Unity Reflect【開発編 ver2.0】
 
徹底解説 Unity Reflect【概要編 ver2.0】
徹底解説 Unity Reflect【概要編 ver2.0】徹底解説 Unity Reflect【概要編 ver2.0】
徹底解説 Unity Reflect【概要編 ver2.0】
 
Unityティーチャートレーニングデイ -認定プログラマー編-
Unityティーチャートレーニングデイ -認定プログラマー編-Unityティーチャートレーニングデイ -認定プログラマー編-
Unityティーチャートレーニングデイ -認定プログラマー編-
 
Unityティーチャートレーニングデイ -認定3Dアーティスト編-
Unityティーチャートレーニングデイ -認定3Dアーティスト編-Unityティーチャートレーニングデイ -認定3Dアーティスト編-
Unityティーチャートレーニングデイ -認定3Dアーティスト編-
 
Unityティーチャートレーニングデイ -認定アソシエイト編-
Unityティーチャートレーニングデイ -認定アソシエイト編-Unityティーチャートレーニングデイ -認定アソシエイト編-
Unityティーチャートレーニングデイ -認定アソシエイト編-
 

Recently uploaded

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 

Recently uploaded (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 

【Unite 2017 Tokyo】パフォーマンス向上のためのスクリプトのベストプラクティス

  • 1. C# Tips and Tricks
  • 3. Plan • The C# compiler • .NET 4.6 • Marshalling • Understanding Boxing, Foreach, Stack vs. Heap allocation • GameManager Singleton pattern
  • 5. C# compiler • The VM is an abstract stack machine • Then, we compile • Source file goes through • Tree builder that results into an • Abstract syntax tree that goes into the • Attribute evaluator that turns into an • Attributed tree that then feeds the • Tree walker that finally generates the • IL
  • 6. C# compiler int SimpleCondition(int input) { if(input >= 0) return input * 2; else return -input; }
  • 9. .NET 4.6 Most notably : • Async • Tasks • DataContracts • Cryptography • Networking
  • 10. .NET 4.6 -> C# 6.0 • Null-Conditional Operator • Auto-Property Initializers • Nameof Expressions • Primary Constructors • Expression Bodied Functions and Properties
  • 11. .NET 4.6 -> C# 6.0
  • 13. .NET 4.6 FAQ • What platforms does this affect? All of them, but in different ways: - Editor and Standalone use the new version of Mono when this option is enabled. - All console platforms will only be able to use IL2CPP when targeting the new .NET version. - iOS and WebGL will continue to be IL2CPP only. - Android will continue to support both Mono and IL2CPP. - Other platforms are still undergoing work to support either new Mono or IL2CPP • What about IL2CPP? IL2CPP fully supports the new .NET 4.6 APIs and features.
  • 14. .NET 4.6 FAQ • What about the a new GC? The newer Mono garbage collector (SGen) requires additional work in Unity and will follow once we have stabilized the new runtime and class libraries. • Why are my builds larger with the new .NET version? The .NET 4.6 class libraries are quite larger than our current .NET 3.5 class libraries. We are actively working on improving the managed linker to reduce size further.
  • 16. What is ‘Unmanaged’ Code? • As the name implies, unmanaged code means YOU are responsible for a host of things, that are usually taken care of for you when using managed code. For example: • Memory management • Thread Synchronization • Security • Life-time control of objects • Etc.
  • 17. Using Unmanaged Code Access managed through DLL / Libraries [DllImport (“YourCode”)] followed by a function name, which needs to be static and extern Place a plugin directory alongside the ‘Assets’ folder in your project and place the library there If you get a “DllNotFoundException” make sure the path is correct and your library is present in the Plugins directory.
  • 18. DLL in Unity Put your plugins in : • Assets/Plugins • Assets/Plugins/x86 • Assets/Plugins/x86_64 Once you have create / compiled and place your DLL / library in the right place, you can call it directly from your managed code.
  • 19. Invoking Unmanaged Code • Generally speaking, you just call the method associated with the DLLImport tag. • Using GetProcAddress(), the specific function is looked up and executed. • Unfortunately, things aren’t that simple (surprise!) • C ABI is used for most calls. • Makes it near impossible to call functions that don’t adhere to this, like C++. • Again, ABI’s are platform specific. • Use either __stdcall and __cdecl for VC++ or __attribute__((stdcall)) and • __attribute__((cdecl)) for GCC. • If you need to invoke C++ code, use ‘extern “C”’ to ensure the calling convention is adhered to.
  • 20. Exceptions • Runtime Exceptions can happen and unmanaged code needs to be able to deal with it. • Unfortunately, C doesn’t support exceptions • C++ does to some extent but has a different mechanism. • Don’t cross the streams and let exceptions propagate between managed and unmanaged code or you run the risk of things going bad
  • 21. Marshalling • Marshalling is the process of ‘converting’ parameters from managed to unmanaged space. • For simple types, this just becomes a straight copy (byte, int, floats, etc) • Sometimes called ‘blitting’ • Bool, Strings, Arrays are a little more complex…. • Depends on what type of string it is: • Ascii, UTF-8, UTF-16, etc. • Memory boundaries need to be kept separate! • Don’t keep references around to managed data! • Data is usually released after call, with obvious consequences. • Possible to lock a memory area by using the C# ’fixed’ statement. • Generally, memory is copied around!
  • 22. Marshalling (Cnt’d) • Strings, Classes and Structs • As mentioned earlier, strings are handled different than blittable data types. • CLR doesn’t just look for single function but function based on the type. I.e. Different functions for different objects passed in. • In order to facilitate this, you can ‘MarshallAs’ and describe your own datatype, as follows: [DllImport (”somedll")] private static extern void Foo ( [MarshalAs(UnmanagedType.LPStr)] string ansiString, [MarshalAs(UnmanagedType.LPWStr)] string unicodeString, [MarshalAs(UnmanagedType.LPTStr)] string platformString );
  • 23. Marshalling (Cnt’d) • Structs and classes can’t be passed by value, only by reference. • Since it’s managed memory, anything that’s copied may move / change. • Generally a bad thing to do anyway! • Structs and classes differ by alignment. • Structs are sequentially aligned by default (as you’d expect) • Classes may or may not be laid out in memory the way you defined them! • If you must have them sequential, use the [StructLayout (LayoutKind.Sequential)] tag. • Return values should be copied back into managed memory.
  • 24. Memory Management / Custom Marshalling • Memory managed owned by CLI will be managed by CLI • I.e. a reference to an object passed down to unmanaged code will be reclaimed by the CLI. • Both managed and unmanaged memory allocations come from the same pool. • Use Marshall.AllocCoTaskMem() and Marshall.FreeCoTaskMem() • Rather than having built-in Marshalling, you can use create custom ones. • Use ‘MarshalAs’ • Remember that you’ll need to write implementations for all variations of objects passed in!
  • 25. Bottom Line • Don’t overlook the impact Marshalling has on your code. • You’re copying memory around! • Make sure you know who owns what. I.e. The CG doesn’t know what you own / use. • Unless you have a valid reason for using unmanaged code, stick to managed code.
  • 26. Example of marshalling struct Boss { char* name; int health; }; int SumBossHealth(Boss* bosses, int size) { int sum = 0; for (int i = 0; i < size; ++i) { sum += bosses[i].health; } return sum; } bool IsBossDead(Boss b) { return b.health == 0; }
  • 27. Example of marshalling [DllImport("__Internal")] [return: MarshalAs(UnmanagedType.U1)] private extern static bool IsBossDead(Boss b); [DllImport("__Internal")] private extern static int SumBossHealth(Boss[] bosses, int size);
  • 28. Example of marshalling Boss[] bosses = {new Boss("First Boss", 25), new Boss("Second Boss", 45)}; Debug.Log (string.Format ("Marshaling a non-blittable struct: {0}", IsBossDead (new Boss("Final Boss", 100)))); Debug.Log(string.Format("Marshaling an array by reference: {0}", SumBossHealth (bosses, bosses.Length)));
  • 30. Best practices - Boxing using UnityEngine; using System.Collections; public class InputAxis : MonoBehaviour { void Update () { float x = Input.GetAxis("Horizontal"); Debug.Log(x); }
  • 31. Best practices extern "C" void InputAxis_Update_m397189571 (InputAxis_t277341211 * __this, const MethodInfo* method) { [...] float V_0 = 0.0f; { IL2CPP_RUNTIME_CLASS_INIT(Input_t1785128008_il2cpp_TypeInfo_var); float L_0 = Input_GetAxis_m2098048324(NULL /*static, unused*/, _stringLiteral855845486, /*hidden argument*/NULL); V_0 = L_0; float L_1 = V_0; float L_2 = L_1; Il2CppObject * L_3 = Box(Single_t2076509932_il2cpp_TypeInfo_var, &L_2); IL2CPP_RUNTIME_CLASS_INIT(Debug_t1368543263_il2cpp_TypeInfo_var); Debug_Log_m920475918(NULL /*static, unused*/, L_3, /*hidden argument*/NULL); return; } }
  • 32. Best practices - Foreach int ForEachArray (int[] items) { var total = 0; foreach (var item in items) total += item; return total; }
  • 33. Best practices - Foreach int ForEachArray(int[] items) { int num = 0; for (int i = 0; i < items.Length; i++) { int num2 = items[i]; num += num2; } return num; }
  • 34. Best practices – Foreach on collections To avoid allocations when using foreach over a collection the following criteria need to be met: - For collections of value types, the collection and enumerator implement the generic interfaces IEnumerable<T> and IEnumerator<T>. - The enumerator implementation is a struct not a class. - The collection has a public method named GetEnumerator whose return type is the enumerator struct. The BCL types System.Collections.Generic.List<T>, System.Collections.Generic.Dictionary<T>, and System.Collections.Generic.HashSet<T> all follow the guidelines above and should be safe to perform foreach statements on.
  • 35. Best practices – Foreach on collections int ForEachCustom (CustomCollection items) { var total = 0; foreach (int item in items) total += item; return total; } Specify the type explicitely -> public class Enumerator : IEnumerator<int>, not just an Enumerator on Systems.Objects (by default). Use a struct and not a class so your when you do new in GetEnumerator, it goes on the stack and not the heap -> return new Enumerator (this);
  • 36. Best practices – Foreach on collections class CustomCollection : IEnumerable<int> { private readonly int[] _items; public CustomCollection(int[] items) { _items = items; } public Enumerator GetEnumerator () { return new Enumerator (this); } IEnumerator<int> IEnumerable<int>.GetEnumerator () { return GetEnumerator (); } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } public struct Enumerator : IEnumerator<int> { private readonly CustomCollection _collection; private int _index; [...] } }
  • 37. Best practices public class ClassVsStruct : MonoBehaviour { struct PointStruct { public int x; public int y; } class PointClass { public int x; public int y; } void Update() { PointStruct ps; ps.x = 3; ps.y = 4; PointStruct ps2 = new PointStruct(); ps2.x = 7; ps2.y = 8; PointClass pc = new PointClass(); pc.x = 5; pc.y = 6; gameObject.transform.position.Set( ps.x + pc.x, ps.y + pc.y, 0); } }
  • 38. .method private hidebysig instance void Update () cil managed { .maxstack 4 .locals init ( [0] valuetype ClassVsStruct/PointStruct, [1] valuetype ClassVsStruct/PointStruct, [2] class ClassVsStruct/PointClass, [3] valuetype [UnityEngine]UnityEngine.Vector3 ) IL_0000: ldloca.s 0 IL_0002: ldc.i4.3 IL_0003: stfld int32 ClassVsStruct/PointStruct::x IL_0008: ldloca.s 0 IL_000a: ldc.i4.4 IL_000b: stfld int32 ClassVsStruct/PointStruct::y IL_0010: ldloca.s 1 IL_0012: initobj ClassVsStruct/PointStruct IL_0018: ldloca.s 1 IL_001a: ldc.i4.7 IL_001b: stfld int32 ClassVsStruct/PointStruct::x IL_0020: ldloca.s 1 IL_0022: ldc.i4.8 IL_0023: stfld int32 ClassVsStruct/PointStruct::y IL_0028: newobj instance void ClassVsStruct/PointClass::.ctor() IL_002d: stloc.2 IL_002e: ldloc.2 IL_002f: ldc.i4.5
  • 39. Best practices • Strings are immutable and will make copies • Use String.Builder • Use a hash to avoid Strings static readonly int material_Color = Shader.PropertyToID(“_Color”); static readonly int anim_Attack = Animator.StringToHash(“attack”); material.SetColor(material_Color, Color.white); animator.SetTrigger(anim_Attack);
  • 40. The GC.Collect myth • There’s a myth saying that when you want to call GC.Collect, you should do it 6 times. • Another myth says it’s 7 times. • Is that really true?
  • 41. The GC.Collect myth • On some platforms the GC can decommit memory from virtual memory • And that happens after so many collections without some pages being needed • But it can never be used by anything other than GC because it is still reserved … that address range is not available for any other allocator in the process • tldr; There isn’t much benefits. Unless you do something wrong and want to be nice to other applications running on that OS.
  • 42. Best practices Vector3.zero really does get { return new Vector3(0,0,0); }
  • 44. GameManager pattern • In this use case, there is a very important lesson to learn. But to show you the lesson, I will do a very common mistake… • The Singleton is a very good candidate that can be called thousands of times per frame • Let’s look at one way to implement it.
  • 45.
  • 46.
  • 48.
  • 49.
  • 51. GameManager pattern • static bool IsNativeObjectAlive(UnityEngine.Object o) • { • #if !UNITY_EDITOR return o.GetCachedPtr() != IntPtr.Zero; #else if (o.GetCachedPtr() != IntPtr.Zero) return true; if (o is MonoBehaviour || o is ScriptableObject) return false; return DoesObjectWithInstanceIDExist(o.GetInstanceID()); #endif }
  • 52. GameManager pattern using UnityEngine.Profiling; public class SingletonCaller : MonoBehaviour { CustomSampler samplerFind; [...] void Start() { samplerFind = CustomSampler.Create("CallSingletonGameFind"); } [...] void Update() { samplerFind.Begin(); CallSingletonGameFind(); samplerFind.End(); } }
  • 54. Never profile a game running in the editor.
  • 55. ? operator string str = null; void Test1() { str?.ToUpper(); } void Test2() { if(str != null) str.ToUpper(); }
  • 57. What about… • MonoBehaviour vs class? • Sealed • Static • Unsafe • LINQ • Generic
  • 59. Conclusion • Some C# keywords are hiding overhead and allocations • Prefer POD and struct of classes • int, float, struct • NOT class, NOT strings • Check the resulting IL • But more importantly than anything else …
  • 60. Only profile if the profiler tells you to do so