SlideShare a Scribd company logo
Maximizing performance of
3D user-generated
assets in Unity
Max Pixel
Freeform Labs
DBA since May 2015
Incorporated March 2016
Your Speaker
2003
Games & Websites as a hobby
2008
Freelance
web development
2011 - 2014 - 2015
USC Film Production
→
Interactive Entertainment
Freeform Labs
Inception Feb 2014
Funded March 2016
Q: Why is it
freezing?
A: GARBAGE
COLLECTIO
N
The Agenda
Optimization principles
Real examples
???
PROFIT
Hands-on Demonstration!
Starting Point:
http://wiki.unity3d.com/index.php/OptimizedTrailRenderer
https://github.com/M-Pixel/unity-procedural-mesh-optimization-presentation
Encapsulation grumble grumble
public float maxAngle → [SerializeField] private float _maxAngle
Hold down alt for magic Buy ReSharper for more magic
Full disclosure: I have no affiliation with ReSharper. They don’t give me money. I just really like it.
Start
private void Start()
{
_trailObj = new GameObject("Trail"); // Why have a game object that just controls another one?
_trailObj.transform.parent = null;
_trailObj.transform.position = Vector3.zero;
_trailObj.transform.rotation = Quaternion.identity;
_trailObj.transform.localScale = Vector3.one;
var meshFilter = (MeshFilter)_trailObj.AddComponent(typeof(MeshFilter));
_mesh = meshFilter.mesh;
_trailObj.AddComponent(typeof(MeshRenderer));
_instanceMaterial = new Material(_material);
_fadeOutRatio = 1f / _instanceMaterial.GetColor("_TintColor").a;
_trailObj.GetComponent<Renderer>().material = _instanceMaterial;
}
Prefer Observation
[SerializeField] private Transform _source;
RequireComponent
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
public class Trail : MonoBehaviour {
Destroy(_trailObj);
Destroy(this); // ???
New Start
private void Start()
{
_mesh = GetComponent<MeshFilter>().mesh;
_instanceMaterial = new Material(_material);
_fadeOutRatio = 1f /
_instanceMaterial.GetColor("_TintColor").a;
_renderer = GetComponent<MeshRenderer>();
_renderer.material = _instanceMaterial;
}
(because the mesh origin needs to
be stationary, that’s why)
Avoid Reflection
if (_pointCnt < 2)
{
_trailObj.GetComponent<Renderer>().enabled = false;
return;
}
_trailObj.GetComponent<Renderer>().enabled = true;
Revised
if (_pointCnt < 2)
{
_renderer.enabled = false;
return;
}
_renderer.enabled = true;
Add to Class
private MeshRenderer _renderer;
In Start
_renderer = GetComponent<MeshRenderer>();
Optimize by actually optimizing, not reducing quality
// Optimization
if (_pointCnt > _optimizeCount)
{
_maxAngle += _optimizeAngleInterval;
_maxVertexDistance += _optimizeDistanceInterval;
_optimizeCount += 1;
}
Heap vs Stack
Long-term, Garbage Collected
● Class instances
● Arrays
○ Even tiny ones (ノಥ益ಥ)ノ
Very short-term
● POD
● Structs
○ … sometimes
Points are being deleted and reallocated at runtime
for (var i = _pointCnt - 1; i >= 0; i--) {
var point = _points[i];
if (point == null || point.TimeAlive > _segmentLifetime) {
_points[i] = null;
_pointCnt--;
} else break;
}
if (_emit) {
if (_pointCnt == 0) {
_points[_pointCnt++] = new Point(_source.transform);
_points[_pointCnt++] = new Point(_source.transform);
}
...
indices > _pointCnt are ignored anyways
for (var i = _pointCnt - 1; i >= 0; i--) {
var point = _points[i];
if (point == null || point.TimeAlive > _segmentLifetime) {
_points[i] = null;
_pointCnt--;
} else break;
}
if (_emit) {
// Make sure there are always at least 2 points when emitting
if (_pointCnt < 2) {
if (_pointCnt < 1) InsertPoint();
InsertPoint();
}
...
RAM & Speed
Putting things away and taking
them out again takes a lot of time
Shifting is unnecessarily expensive
Removing old points
for (var i = _pointCnt - 1; i >= 0; i--){
var point = _points[i];
if (point.TimeAlive >
_segmentLifetime) {
_pointCnt--;
} else break;
}
Adding new points
for(int i = pointCnt; i > 0; i--)
points[i] = points[i-1];
points[0] = new Point(transform);
pointCnt++;
What about adding new points on top of the
array?
Just reverses problem
What about a Queue?
Yes!
using (var e = _ints.GetEnumerator()) {
while (e.MoveNext()) {
_current += e.Current;
}
}
for (var i = 0; i < _ints.Count; i++) {
var item = _ints.Dequeue();
_current += item;
_ints.Enqueue(item);
}
Unity’s Enumerator Problem
Temporary Arrays
// Rebuild it
var vertices = new Vector3[pointCount * 2];
var uvs = new Vector2[pointCount * 2];
var triangles = new int[(pointCount - 1) * 6];
var meshColors = new Color[pointCount * 2];
5.3 MB/s
Comparing Distance
var sqrDistance = (
_points[1].Position -
_source.transform.position
).sqrMagnitude;
if (sqrDistance > _minVertexDistance * _minVertexDistance)
{
…
}
if (Vector3.Dot(a, b) > _preSquaredBasis) …
Comparing Distance
a2 + b2 = c2
a2 + b2 + c2 = d2
d = sqrt ( a2 + b2 + c2 )
Square root is a relatively expensive operation
Dot == a2 + b2 + c2
Vector3.Distance == Sqrt ( Dot ( A , B ) )
Comparing dots is faster than comparing distances
Double trouble: Unity’s Vector3.Dot uses doubles
Other Optimizations
Use arrays for vertex, color, uv buffers (triangle buffer must be a List)
Make Point a struct (Pre-allocate)
Eliminate (inline) pool
Eliminate Points altogether, work directly with vertices?
What about extra vertices?
It turns out, any number of extra
verts/colors/etc. have negligible impact
Only triangles matter!
mesh.SetTriangles takes a List
The final result...
34 to 60KB garbage + .41ms
vs
0B garbage + .24ms
(per frame)
Takeaways
Use the Unity Profiler’s gcalloc column to find out where heap allocation occurs
First use utilities like Queue, List to eliminate GC, then once your pattern is confirmed
to work and the design is locked down, you can refactor to naked arrays
Reuse Arrays, Delegates, G.O.s whenever possible
Start/end indexes
Pool unused instances
Don’t use IEnumerators, find a workaround
When comparing distances, use Dot instead of Distance
Thank you!
max@freeformlabs.xyz

More Related Content

What's hot

Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks
Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeksBeginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks
Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks
JinTaek Seo
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Ankit Kumar
 
Introduction of 3D Development
Introduction of 3D DevelopmentIntroduction of 3D Development
Introduction of 3D Development
siufu
 
Computer graphics practical(jainam)
Computer graphics practical(jainam)Computer graphics practical(jainam)
Computer graphics practical(jainam)
JAINAM KAPADIYA
 
Lec02 03 rasterization
Lec02 03 rasterizationLec02 03 rasterization
Lec02 03 rasterization
Maaz Rizwan
 
Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5
Takao Wada
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to Tensorflow
Khor SoonHin
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Uma mohan
 
Unit 3
Unit 3Unit 3
Computer Graphics Unit 1
Computer Graphics Unit 1Computer Graphics Unit 1
Computer Graphics Unit 1
aravindangc
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3
Khor SoonHin
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.
UA Mobile
 
Google TensorFlow Tutorial
Google TensorFlow TutorialGoogle TensorFlow Tutorial
Google TensorFlow Tutorial
台灣資料科學年會
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
Vivek Kumar Sinha
 
Circular Convolution
Circular ConvolutionCircular Convolution
Circular Convolution
Sarang Joshi
 

What's hot (20)

Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks
Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeksBeginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks
Beginning direct3d gameprogramming10_shaderdetail_20160506_jintaeks
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Introduction of 3D Development
Introduction of 3D DevelopmentIntroduction of 3D Development
Introduction of 3D Development
 
Computer graphics practical(jainam)
Computer graphics practical(jainam)Computer graphics practical(jainam)
Computer graphics practical(jainam)
 
Lec02 03 rasterization
Lec02 03 rasterizationLec02 03 rasterization
Lec02 03 rasterization
 
Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5Trident International Graphics Workshop 2014 4/5
Trident International Graphics Workshop 2014 4/5
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to Tensorflow
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Cgm Lab Manual
Cgm Lab ManualCgm Lab Manual
Cgm Lab Manual
 
Unit 3
Unit 3Unit 3
Unit 3
 
Real life XNA
Real life XNAReal life XNA
Real life XNA
 
Computer Graphics Unit 1
Computer Graphics Unit 1Computer Graphics Unit 1
Computer Graphics Unit 1
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3
 
cpp_sample
cpp_samplecpp_sample
cpp_sample
 
Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.Gems of GameplayKit. UA Mobile 2017.
Gems of GameplayKit. UA Mobile 2017.
 
09 Simulation
09 Simulation09 Simulation
09 Simulation
 
Google TensorFlow Tutorial
Google TensorFlow TutorialGoogle TensorFlow Tutorial
Google TensorFlow Tutorial
 
COMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUALCOMPUTER GRAPHICS LAB MANUAL
COMPUTER GRAPHICS LAB MANUAL
 
cluster(python)
cluster(python)cluster(python)
cluster(python)
 
Circular Convolution
Circular ConvolutionCircular Convolution
Circular Convolution
 

Viewers also liked

UX and Interaction in Virtual Reality
UX and Interaction in Virtual RealityUX and Interaction in Virtual Reality
UX and Interaction in Virtual Reality
DevGAMM Conference
 
Wizdish rovr
Wizdish rovrWizdish rovr
Wizdish rovr
WithTheBest
 
How to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie StudioHow to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie Studio
WithTheBest
 
VR, a new technology over 40,000 years old
VR, a new technology over 40,000 years oldVR, a new technology over 40,000 years old
VR, a new technology over 40,000 years old
WithTheBest
 
Measuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VRMeasuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VR
WithTheBest
 
How we use vr to break the laws of physics
How we use vr to break the laws of physicsHow we use vr to break the laws of physics
How we use vr to break the laws of physics
WithTheBest
 
Building your own video devices
Building your own video devicesBuilding your own video devices
Building your own video devices
WithTheBest
 
Developing for Room-Scale VR Using Unity3d
Developing for Room-Scale VR Using Unity3dDeveloping for Room-Scale VR Using Unity3d
Developing for Room-Scale VR Using Unity3d
Rising Media, Inc.
 
Mixed reality 101
Mixed reality 101 Mixed reality 101
Mixed reality 101
WithTheBest
 
Transported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estateTransported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estate
WithTheBest
 
You dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helpsYou dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helps
WithTheBest
 
Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode. Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode.
WithTheBest
 
Haptics & amp; null space vr
Haptics & amp; null space vrHaptics & amp; null space vr
Haptics & amp; null space vr
WithTheBest
 
VR Interactions - Jason Jerald
VR Interactions - Jason JeraldVR Interactions - Jason Jerald
VR Interactions - Jason Jerald
WithTheBest
 
The Virtual Self
The Virtual Self The Virtual Self
The Virtual Self
WithTheBest
 
Recreating history in virtual reality
Recreating history in virtual realityRecreating history in virtual reality
Recreating history in virtual reality
WithTheBest
 
Engaging and sharing your VR experience
Engaging and sharing your VR experienceEngaging and sharing your VR experience
Engaging and sharing your VR experience
WithTheBest
 
Unlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive TechnologyUnlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive Technology
WithTheBest
 
Japheth Funding your startup - dating the devil
Japheth  Funding your startup - dating the devilJapheth  Funding your startup - dating the devil
Japheth Funding your startup - dating the devil
WithTheBest
 
Cryptocurrencies, Blockchain & Smart Contracts: The New Wave of Decentralizat...
Cryptocurrencies, Blockchain & Smart Contracts:The New Wave of Decentralizat...Cryptocurrencies, Blockchain & Smart Contracts:The New Wave of Decentralizat...
Cryptocurrencies, Blockchain & Smart Contracts: The New Wave of Decentralizat...
Raffaele Mauro
 

Viewers also liked (20)

UX and Interaction in Virtual Reality
UX and Interaction in Virtual RealityUX and Interaction in Virtual Reality
UX and Interaction in Virtual Reality
 
Wizdish rovr
Wizdish rovrWizdish rovr
Wizdish rovr
 
How to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie StudioHow to survive the early days of VR as an Indie Studio
How to survive the early days of VR as an Indie Studio
 
VR, a new technology over 40,000 years old
VR, a new technology over 40,000 years oldVR, a new technology over 40,000 years old
VR, a new technology over 40,000 years old
 
Measuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VRMeasuring Behavior in VR - Rob Merki Cognitive VR
Measuring Behavior in VR - Rob Merki Cognitive VR
 
How we use vr to break the laws of physics
How we use vr to break the laws of physicsHow we use vr to break the laws of physics
How we use vr to break the laws of physics
 
Building your own video devices
Building your own video devicesBuilding your own video devices
Building your own video devices
 
Developing for Room-Scale VR Using Unity3d
Developing for Room-Scale VR Using Unity3dDeveloping for Room-Scale VR Using Unity3d
Developing for Room-Scale VR Using Unity3d
 
Mixed reality 101
Mixed reality 101 Mixed reality 101
Mixed reality 101
 
Transported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estateTransported vr the virtual reality platform for real estate
Transported vr the virtual reality platform for real estate
 
You dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helpsYou dont have to be mad to do VR and AR ... but it helps
You dont have to be mad to do VR and AR ... but it helps
 
Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode. Global demand for Mixed Realty (VR/AR) content is about to explode.
Global demand for Mixed Realty (VR/AR) content is about to explode.
 
Haptics & amp; null space vr
Haptics & amp; null space vrHaptics & amp; null space vr
Haptics & amp; null space vr
 
VR Interactions - Jason Jerald
VR Interactions - Jason JeraldVR Interactions - Jason Jerald
VR Interactions - Jason Jerald
 
The Virtual Self
The Virtual Self The Virtual Self
The Virtual Self
 
Recreating history in virtual reality
Recreating history in virtual realityRecreating history in virtual reality
Recreating history in virtual reality
 
Engaging and sharing your VR experience
Engaging and sharing your VR experienceEngaging and sharing your VR experience
Engaging and sharing your VR experience
 
Unlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive TechnologyUnlocking Human Potential with Immersive Technology
Unlocking Human Potential with Immersive Technology
 
Japheth Funding your startup - dating the devil
Japheth  Funding your startup - dating the devilJapheth  Funding your startup - dating the devil
Japheth Funding your startup - dating the devil
 
Cryptocurrencies, Blockchain & Smart Contracts: The New Wave of Decentralizat...
Cryptocurrencies, Blockchain & Smart Contracts:The New Wave of Decentralizat...Cryptocurrencies, Blockchain & Smart Contracts:The New Wave of Decentralizat...
Cryptocurrencies, Blockchain & Smart Contracts: The New Wave of Decentralizat...
 

Similar to Maximizing performance of 3 d user generated assets in unity

Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Brendan Eich
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Romain Dorgueil
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
Fwdays
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
Dina Goldshtein
 
Seeing Like Software
Seeing Like SoftwareSeeing Like Software
Seeing Like Software
Andrew Lovett-Barron
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
Yung-Yu Chen
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
Brendan Eich
 
A Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and AllegroA Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and Allegro
snowfarthing
 
Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014
Dieter Plaetinck
 
ITT 2014 - Chris Eidhof - Practical Concurrent Programming
ITT 2014 - Chris Eidhof - Practical Concurrent ProgrammingITT 2014 - Chris Eidhof - Practical Concurrent Programming
ITT 2014 - Chris Eidhof - Practical Concurrent Programming
Istanbul Tech Talks
 
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
LogeekNightUkraine
 
Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...
Paweł Żurowski
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Languagemspline
 
3 mathematical challenge_code
3 mathematical challenge_code3 mathematical challenge_code
3 mathematical challenge_codeRussell Childs
 
Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5
Takao Wada
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019
chayanikaa
 
A practical work of matlab
A practical work of matlabA practical work of matlab
A practical work of matlab
SalanSD
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
ShaiAlmog1
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
Remy Sharp
 

Similar to Maximizing performance of 3 d user generated assets in unity (20)

Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache AirflowBusiness Dashboards using Bonobo ETL, Grafana and Apache Airflow
Business Dashboards using Bonobo ETL, Grafana and Apache Airflow
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
What's New in C++ 11/14?
What's New in C++ 11/14?What's New in C++ 11/14?
What's New in C++ 11/14?
 
Seeing Like Software
Seeing Like SoftwareSeeing Like Software
Seeing Like Software
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
 
A Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and AllegroA Simple 3D Graphics Engine Written in Python and Allegro
A Simple 3D Graphics Engine Written in Python and Allegro
 
Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014Rethinking metrics: metrics 2.0 @ Lisa 2014
Rethinking metrics: metrics 2.0 @ Lisa 2014
 
ITT 2014 - Chris Eidhof - Practical Concurrent Programming
ITT 2014 - Chris Eidhof - Practical Concurrent ProgrammingITT 2014 - Chris Eidhof - Practical Concurrent Programming
ITT 2014 - Chris Eidhof - Practical Concurrent Programming
 
Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"Yevhen Tatarynov "From POC to High-Performance .NET applications"
Yevhen Tatarynov "From POC to High-Performance .NET applications"
 
Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...Architecture for scalable Angular applications (with introduction and extende...
Architecture for scalable Angular applications (with introduction and extende...
 
C++11: Feel the New Language
C++11: Feel the New LanguageC++11: Feel the New Language
C++11: Feel the New Language
 
3 mathematical challenge_code
3 mathematical challenge_code3 mathematical challenge_code
3 mathematical challenge_code
 
Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5Trident International Graphics Workshop 2014 1/5
Trident International Graphics Workshop 2014 1/5
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
 
Whats new in ES2019
Whats new in ES2019Whats new in ES2019
Whats new in ES2019
 
A practical work of matlab
A practical work of matlabA practical work of matlab
A practical work of matlab
 
Creating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdfCreating an Uber Clone - Part IV - Transcript.pdf
Creating an Uber Clone - Part IV - Transcript.pdf
 
HTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymoreHTML5: where flash isn't needed anymore
HTML5: where flash isn't needed anymore
 

More from WithTheBest

Riccardo Vittoria
Riccardo VittoriaRiccardo Vittoria
Riccardo Vittoria
WithTheBest
 
Omnivirt overview
Omnivirt overviewOmnivirt overview
Omnivirt overview
WithTheBest
 
Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...
Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...
Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...
WithTheBest
 
From Coffee to Cloud
From Coffee to CloudFrom Coffee to Cloud
From Coffee to Cloud
WithTheBest
 
HP Wearables and IoT - Our Story - Christine Hawkins
HP Wearables and IoT - Our Story - Christine HawkinsHP Wearables and IoT - Our Story - Christine Hawkins
HP Wearables and IoT - Our Story - Christine Hawkins
WithTheBest
 
IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...
IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...
IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...
WithTheBest
 
Deploying IoT to Support Low-Income Seniors at Home - Sombit Mishra
Deploying IoT to Support Low-Income Seniors at Home - Sombit MishraDeploying IoT to Support Low-Income Seniors at Home - Sombit Mishra
Deploying IoT to Support Low-Income Seniors at Home - Sombit Mishra
WithTheBest
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
WithTheBest
 
Ambient Intelligence - Parham Beheshti
Ambient Intelligence - Parham BeheshtiAmbient Intelligence - Parham Beheshti
Ambient Intelligence - Parham Beheshti
WithTheBest
 
Moving Beyond Technology-That-Works to Products-That-Matter
Moving Beyond Technology-That-Works to Products-That-MatterMoving Beyond Technology-That-Works to Products-That-Matter
Moving Beyond Technology-That-Works to Products-That-Matter
WithTheBest
 
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter ObiltschnigMastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
WithTheBest
 
Rapid IoT Application Development with IBM Bluemix - Mikko Poutanen
Rapid IoT Application Development with IBM Bluemix - Mikko PoutanenRapid IoT Application Development with IBM Bluemix - Mikko Poutanen
Rapid IoT Application Development with IBM Bluemix - Mikko Poutanen
WithTheBest
 
IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...
IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...
IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...
WithTheBest
 

More from WithTheBest (13)

Riccardo Vittoria
Riccardo VittoriaRiccardo Vittoria
Riccardo Vittoria
 
Omnivirt overview
Omnivirt overviewOmnivirt overview
Omnivirt overview
 
Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...
Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...
Getting Started with Intelligent IoT Messaging - Ken Herron, Emy Carlan, and ...
 
From Coffee to Cloud
From Coffee to CloudFrom Coffee to Cloud
From Coffee to Cloud
 
HP Wearables and IoT - Our Story - Christine Hawkins
HP Wearables and IoT - Our Story - Christine HawkinsHP Wearables and IoT - Our Story - Christine Hawkins
HP Wearables and IoT - Our Story - Christine Hawkins
 
IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...
IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...
IoT: From Arduino MicroControllers to Tizen Products Using IoTivity - Philipp...
 
Deploying IoT to Support Low-Income Seniors at Home - Sombit Mishra
Deploying IoT to Support Low-Income Seniors at Home - Sombit MishraDeploying IoT to Support Low-Income Seniors at Home - Sombit Mishra
Deploying IoT to Support Low-Income Seniors at Home - Sombit Mishra
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
 
Ambient Intelligence - Parham Beheshti
Ambient Intelligence - Parham BeheshtiAmbient Intelligence - Parham Beheshti
Ambient Intelligence - Parham Beheshti
 
Moving Beyond Technology-That-Works to Products-That-Matter
Moving Beyond Technology-That-Works to Products-That-MatterMoving Beyond Technology-That-Works to Products-That-Matter
Moving Beyond Technology-That-Works to Products-That-Matter
 
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter ObiltschnigMastering the IoT With JavaScript and C++ - Günter Obiltschnig
Mastering the IoT With JavaScript and C++ - Günter Obiltschnig
 
Rapid IoT Application Development with IBM Bluemix - Mikko Poutanen
Rapid IoT Application Development with IBM Bluemix - Mikko PoutanenRapid IoT Application Development with IBM Bluemix - Mikko Poutanen
Rapid IoT Application Development with IBM Bluemix - Mikko Poutanen
 
IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...
IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...
IBM's Watson IoT Platform Allows You to Quickly Connect Devices to Bluemix Cl...
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 

Maximizing performance of 3 d user generated assets in unity

  • 1. Maximizing performance of 3D user-generated assets in Unity Max Pixel Freeform Labs
  • 2. DBA since May 2015 Incorporated March 2016 Your Speaker 2003 Games & Websites as a hobby 2008 Freelance web development 2011 - 2014 - 2015 USC Film Production → Interactive Entertainment Freeform Labs Inception Feb 2014 Funded March 2016
  • 3.
  • 4.
  • 5. Q: Why is it freezing?
  • 9. Encapsulation grumble grumble public float maxAngle → [SerializeField] private float _maxAngle Hold down alt for magic Buy ReSharper for more magic Full disclosure: I have no affiliation with ReSharper. They don’t give me money. I just really like it.
  • 10. Start private void Start() { _trailObj = new GameObject("Trail"); // Why have a game object that just controls another one? _trailObj.transform.parent = null; _trailObj.transform.position = Vector3.zero; _trailObj.transform.rotation = Quaternion.identity; _trailObj.transform.localScale = Vector3.one; var meshFilter = (MeshFilter)_trailObj.AddComponent(typeof(MeshFilter)); _mesh = meshFilter.mesh; _trailObj.AddComponent(typeof(MeshRenderer)); _instanceMaterial = new Material(_material); _fadeOutRatio = 1f / _instanceMaterial.GetColor("_TintColor").a; _trailObj.GetComponent<Renderer>().material = _instanceMaterial; } Prefer Observation [SerializeField] private Transform _source; RequireComponent [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] public class Trail : MonoBehaviour { Destroy(_trailObj); Destroy(this); // ??? New Start private void Start() { _mesh = GetComponent<MeshFilter>().mesh; _instanceMaterial = new Material(_material); _fadeOutRatio = 1f / _instanceMaterial.GetColor("_TintColor").a; _renderer = GetComponent<MeshRenderer>(); _renderer.material = _instanceMaterial; } (because the mesh origin needs to be stationary, that’s why)
  • 11. Avoid Reflection if (_pointCnt < 2) { _trailObj.GetComponent<Renderer>().enabled = false; return; } _trailObj.GetComponent<Renderer>().enabled = true; Revised if (_pointCnt < 2) { _renderer.enabled = false; return; } _renderer.enabled = true; Add to Class private MeshRenderer _renderer; In Start _renderer = GetComponent<MeshRenderer>();
  • 12. Optimize by actually optimizing, not reducing quality // Optimization if (_pointCnt > _optimizeCount) { _maxAngle += _optimizeAngleInterval; _maxVertexDistance += _optimizeDistanceInterval; _optimizeCount += 1; }
  • 13. Heap vs Stack Long-term, Garbage Collected ● Class instances ● Arrays ○ Even tiny ones (ノಥ益ಥ)ノ Very short-term ● POD ● Structs ○ … sometimes
  • 14. Points are being deleted and reallocated at runtime for (var i = _pointCnt - 1; i >= 0; i--) { var point = _points[i]; if (point == null || point.TimeAlive > _segmentLifetime) { _points[i] = null; _pointCnt--; } else break; } if (_emit) { if (_pointCnt == 0) { _points[_pointCnt++] = new Point(_source.transform); _points[_pointCnt++] = new Point(_source.transform); } ...
  • 15. indices > _pointCnt are ignored anyways for (var i = _pointCnt - 1; i >= 0; i--) { var point = _points[i]; if (point == null || point.TimeAlive > _segmentLifetime) { _points[i] = null; _pointCnt--; } else break; } if (_emit) { // Make sure there are always at least 2 points when emitting if (_pointCnt < 2) { if (_pointCnt < 1) InsertPoint(); InsertPoint(); } ...
  • 16. RAM & Speed Putting things away and taking them out again takes a lot of time
  • 17. Shifting is unnecessarily expensive Removing old points for (var i = _pointCnt - 1; i >= 0; i--){ var point = _points[i]; if (point.TimeAlive > _segmentLifetime) { _pointCnt--; } else break; } Adding new points for(int i = pointCnt; i > 0; i--) points[i] = points[i-1]; points[0] = new Point(transform); pointCnt++; What about adding new points on top of the array? Just reverses problem What about a Queue? Yes!
  • 18. using (var e = _ints.GetEnumerator()) { while (e.MoveNext()) { _current += e.Current; } } for (var i = 0; i < _ints.Count; i++) { var item = _ints.Dequeue(); _current += item; _ints.Enqueue(item); } Unity’s Enumerator Problem
  • 19. Temporary Arrays // Rebuild it var vertices = new Vector3[pointCount * 2]; var uvs = new Vector2[pointCount * 2]; var triangles = new int[(pointCount - 1) * 6]; var meshColors = new Color[pointCount * 2]; 5.3 MB/s
  • 20. Comparing Distance var sqrDistance = ( _points[1].Position - _source.transform.position ).sqrMagnitude; if (sqrDistance > _minVertexDistance * _minVertexDistance) { … } if (Vector3.Dot(a, b) > _preSquaredBasis) …
  • 21. Comparing Distance a2 + b2 = c2 a2 + b2 + c2 = d2 d = sqrt ( a2 + b2 + c2 ) Square root is a relatively expensive operation Dot == a2 + b2 + c2 Vector3.Distance == Sqrt ( Dot ( A , B ) ) Comparing dots is faster than comparing distances Double trouble: Unity’s Vector3.Dot uses doubles
  • 22. Other Optimizations Use arrays for vertex, color, uv buffers (triangle buffer must be a List) Make Point a struct (Pre-allocate) Eliminate (inline) pool Eliminate Points altogether, work directly with vertices?
  • 23. What about extra vertices? It turns out, any number of extra verts/colors/etc. have negligible impact Only triangles matter! mesh.SetTriangles takes a List
  • 25. 34 to 60KB garbage + .41ms vs 0B garbage + .24ms (per frame)
  • 26. Takeaways Use the Unity Profiler’s gcalloc column to find out where heap allocation occurs First use utilities like Queue, List to eliminate GC, then once your pattern is confirmed to work and the design is locked down, you can refactor to naked arrays Reuse Arrays, Delegates, G.O.s whenever possible Start/end indexes Pool unused instances Don’t use IEnumerators, find a workaround When comparing distances, use Dot instead of Distance

Editor's Notes

  1. Going to rush through this a bit, not as important as later stuff
  2. Recommend setting up Visual Studio/Rider to color structs and classes differently Visual Studio extension
  3. Note brackets
  4. Note brackets
  5. 32B/frame is almost 3KB/second @ 90fps Method takes twice as long
  6. At 90fps, you have 11ms per frame. Practically, script has ~6-8ms. 3%