-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEntityComponentSystemObjectOrientatedVsDataOrientated.cs
382 lines (317 loc) · 12.7 KB
/
EntityComponentSystemObjectOrientatedVsDataOrientated.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
// This demo explores an entity component system built using object orientated programming
// vs a data orientated approach.
//
// Compares three different ways of processing particles bouncing in a box:
//
// Traditional object orientated programming:
// 1) Entity with multiple components (entity component system).
//
// Data orientated design:
// 2) Entity that is an index into arrays of components. Uses an event component with an updated flag to trigger processing.
// 3) Same as above but instead of using an event component uses a list of bounce events that is processed each iteration (event queue).
//
// Notes:
// - Data orientated is faster even when the OOP objects are created close together in time which should have placed them
// close together in memory.
// - Having a component that is only processed for a small proportion of the entities appears to be slower. I imagine there is break even point
// where above which it is more efficient for every entity to pass events in a component.
namespace EntityComponentSystemObjectOrientatedVsDataOrientated
{
public static class Settings
{
public const int NUM_PARTICLES = 5000000;
public const int GRID_SIZE = NUM_PARTICLES;
public const int MAX_VELOCITY = 100;
public const int BYTES_IN_MB = 1000000;
public const int ITERATIONS = 50;
}
public struct Position
{
public int X;
public int Y;
}
public struct Velocity
{
public int X;
public int Y;
}
public static class SimulateTraditionalOOPEntityComponent
{
private abstract class Entity
{
public int Id;
public IList<Component> Components;
public abstract bool Update();
}
private abstract class Component
{
public abstract void Update(Entity entity);
}
private class MovementComponent : Component
{
public Position Position;
public Velocity Velocity;
public MovementComponent(int posX, int posY, int velX, int velY)
{
Position.X = posX;
Position.Y = posY;
Velocity.X = velX;
Velocity.Y = velY;
}
public override void Update(Entity entity)
{
Position.X += Velocity.X;
Position.Y += Velocity.Y;
}
}
private class BounceComponent : Component
{
private MovementComponent _move;
public BounceComponent(MovementComponent comp)
{
_move = comp;
}
public override void Update(Entity entity)
{
if (_move.Position.X < 0 || _move.Position.X > Settings.GRID_SIZE)
{
_move.Velocity.X = -_move.Velocity.X;
(entity as Particle).bouncedLastUpdate = true;
}
else if (_move.Position.Y < 0 || _move.Position.Y > Settings.GRID_SIZE)
{
_move.Velocity.Y = -_move.Velocity.Y;
(entity as Particle).bouncedLastUpdate = true;
}
}
}
private class Particle : Entity
{
public bool bouncedLastUpdate;
public Particle(int id, IEnumerable<Component> components)
{
Id = id;
Components = components.ToList();
}
/// <returns>True if particle bounced</returns>
public override bool Update()
{
foreach (var comp in Components)
{
comp.Update(this);
}
if (bouncedLastUpdate)
{
bouncedLastUpdate = false;
return true;
}
return false;
}
}
private static System.Diagnostics.Stopwatch s = new Stopwatch();
public static void Run()
{
Particle[] particles = Enumerable.Range(0, Settings.NUM_PARTICLES)
.Select(i =>
{
var move = new MovementComponent(posX: i % Settings.GRID_SIZE, posY: i % Settings.GRID_SIZE, velX: i % Settings.MAX_VELOCITY + 1, velY: i % Settings.MAX_VELOCITY + 1);
var bounce = new BounceComponent(move);
return new Particle(i, new Component[] { move, bounce });
})
.ToArray();
s.Start();
s.Restart();
for (var i = 0; i < Settings.ITERATIONS; ++i)
{
var bounces = 0;
foreach (var particle in particles)
{
if (particle.Update()) { ++bounces; }
}
Console.WriteLine("Time {0} Bounces: {1}", s.ElapsedMilliseconds, bounces);
}
s.Stop();
Console.WriteLine("Average time per iteration: " + s.ElapsedMilliseconds / Settings.ITERATIONS);
}
}
public static class SimulateComponentsWithEventComponent
{
private struct BounceEvent
{
public bool Updated;
public bool FlipX;
public bool FlipY;
}
private static System.Diagnostics.Stopwatch s = new Stopwatch();
public static void Run()
{
Position[] positions = Enumerable.Range(0, Settings.NUM_PARTICLES)
.Select(x => new Position { X = x % Settings.GRID_SIZE, Y = x % Settings.GRID_SIZE })
.ToArray();
Console.WriteLine("Positions [] size: {0} MB", Marshal.SizeOf(typeof(Position)) * positions.Length / Settings.BYTES_IN_MB);
Velocity[] velocities = Enumerable.Range(0, Settings.NUM_PARTICLES)
.Select(x => new Velocity { X = x % Settings.MAX_VELOCITY + 1, Y = x % Settings.MAX_VELOCITY + 1 })
.ToArray();
Console.WriteLine("Velocities [] size: {0} MB", Marshal.SizeOf(typeof(Velocity)) * positions.Length / Settings.BYTES_IN_MB);
BounceEvent[] bounces = Enumerable.Range(0, Settings.NUM_PARTICLES)
.Select(x => new BounceEvent())
.ToArray();
Console.WriteLine("bounceEvents [] size: {0} MB", Marshal.SizeOf(typeof(BounceEvent)) * positions.Length / Settings.BYTES_IN_MB);
s.Start();
s.Restart();
for (var i = 0; i < Settings.ITERATIONS; ++i)
{
ProcessMovement(positions, velocities, bounces);
var numBounces = CountBounces(bounces);
ProcessBounces(velocities, bounces);
Console.WriteLine("Time {0} Bounces: {1}", s.ElapsedMilliseconds, numBounces);
}
s.Stop();
Console.WriteLine("Average time per iteration: " + s.ElapsedMilliseconds / Settings.ITERATIONS);
}
private static void ProcessMovement(Position[] positions, Velocity[] velocities, BounceEvent[] bounces)
{
for (var i = 0; i < Settings.NUM_PARTICLES; ++i)
{
positions[i].X = positions[i].X + velocities[i].X;
positions[i].Y = positions[i].Y + velocities[i].Y;
if (positions[i].X < 0 || positions[i].X > Settings.GRID_SIZE)
{
bounces[i].Updated = true;
bounces[i].FlipX = true;
}
else if (positions[i].Y < 0 || positions[i].Y > Settings.GRID_SIZE)
{
bounces[i].Updated = true;
bounces[i].FlipY = true;
}
}
}
private static int CountBounces(BounceEvent[] bounces)
{
var numEvents = 0;
for (var i = 0; i < Settings.NUM_PARTICLES; ++i)
{
if (bounces[i].FlipX)
{
++numEvents;
}
if (bounces[i].FlipY)
{
++numEvents;
}
}
return numEvents;
}
private static void ProcessBounces(Velocity[] velocities, BounceEvent[] bounces)
{
for (var i = 0; i < Settings.NUM_PARTICLES; ++i)
{
if (!bounces[i].Updated)
{
continue;
}
if (bounces[i].FlipX)
{
bounces[i].FlipX = false;
velocities[i].X = -velocities[i].X;
}
if (bounces[i].FlipY)
{
bounces[i].FlipY = false;
velocities[i].Y = -velocities[i].Y;
}
bounces[i].Updated = false;
}
}
}
public static class SimulateComponentsWithEventQueue
{
private struct BounceEventWithId
{
public int Id;
public bool FlipX;
public bool FlipY;
}
private static System.Diagnostics.Stopwatch s = new Stopwatch();
public static void Run()
{
Position[] positions = Enumerable.Range(0, Settings.NUM_PARTICLES)
.Select(pos => new Position { X = pos % Settings.GRID_SIZE, Y = pos % Settings.GRID_SIZE })
.ToArray();
Console.WriteLine("Positions [] size: {0} MB", Marshal.SizeOf(typeof(Position)) * positions.Length / Settings.BYTES_IN_MB);
Velocity[] velocities = Enumerable.Range(0, Settings.NUM_PARTICLES)
.Select(x => new Velocity { X = x % Settings.MAX_VELOCITY + 1, Y = x % Settings.MAX_VELOCITY + 1 })
.ToArray();
Console.WriteLine("Velocities [] size: {0} MB", Marshal.SizeOf(typeof(Velocity)) * positions.Length / Settings.BYTES_IN_MB);
IList<BounceEventWithId> bounces = new List<BounceEventWithId>();
s.Start();
s.Restart();
for (var i = 0; i < Settings.ITERATIONS; ++i)
{
ProcessMovement(positions, velocities, bounces);
// Note: Bounce events should have been added in increasing order.
ProcessBounces(velocities, bounces);
Console.WriteLine("Time {0} Bounces: {1}", s.ElapsedMilliseconds, bounces.Count);
bounces.Clear();
}
s.Stop();
Console.WriteLine("Average time per iteration: " + s.ElapsedMilliseconds / Settings.ITERATIONS);
}
private static void ProcessMovement(Position[] positions, Velocity[] velocities, IList<BounceEventWithId> bounces)
{
for (var i = 0; i < Settings.NUM_PARTICLES; ++i)
{
positions[i].X = positions[i].X + velocities[i].X;
positions[i].Y = positions[i].Y + velocities[i].Y;
if (positions[i].X < 0 || positions[i].X > Settings.GRID_SIZE)
{
bounces.Add(new BounceEventWithId { Id = i, FlipX = true });
}
else if (positions[i].Y < 0 || positions[i].Y > Settings.GRID_SIZE)
{
bounces.Add(new BounceEventWithId { Id = i, FlipY = true });
}
}
}
private static void ProcessBounces(Velocity[] velocities, IList<BounceEventWithId> bounces)
{
foreach(var bounceEvent in bounces)
{
if (bounceEvent.FlipX)
{
velocities[bounceEvent.Id].X = -velocities[bounceEvent.Id].X;
}
else if (bounceEvent.FlipY)
{
velocities[bounceEvent.Id].Y = -velocities[bounceEvent.Id].Y;
}
}
}
}
public static class Program
{
static void Main(string[] args)
{
GC.Collect();
Console.WriteLine("\n[Press any key to start SimulateTraditionalOOPEntityComponent demo]");
Console.ReadKey();
SimulateTraditionalOOPEntityComponent.Run();
GC.Collect();
Console.WriteLine("\n[Press any key to start SimulateComponentsWithEventComponent demo]");
Console.ReadKey();
SimulateComponentsWithEventComponent.Run();
GC.Collect();
Console.WriteLine("\n[Press any key to start SimulateComponentsWithEventQueue demo]");
Console.ReadKey();
SimulateComponentsWithEventQueue.Run();
Console.WriteLine("\n[Press any key to exit]");
Console.ReadKey();
}
}
}