-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathBetterList.cs
675 lines (558 loc) · 18.5 KB
/
BetterList.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2016 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
using System.Collections.Generic;
using System.Diagnostics;
using System;
/// <summary>
/// This improved version of the System.Collections.Generic.List that doesn't release the buffer on Clear(),
/// resulting in better performance and less garbage collection.
/// PRO: BetterList performs faster than List when you Add and Remove items (although slower if you remove from the beginning).
/// CON: BetterList performs worse when sorting the list. If your operations involve sorting, use the standard List instead.
/// </summary>
public class BufferPoolNodeList<T>
{
public T[] buffer;
private int size = 0;
public void Add(T item)
{
if (buffer == null || size == buffer.Length) EnsureCapacity();
buffer[size++] = item;
}
public void Insert(int index, T item)
{
if (buffer == null || size == buffer.Length) EnsureCapacity();
if (index > -1 && index < size)
{
Array.ConstrainedCopy(buffer, index, buffer, index + 1, size - index);
buffer[index] = item;
++size;
}
else Add(item);
}
public int Count()
{
return size;
}
private void EnsureCapacity()
{
int newCapacity = buffer == null ? 4 : buffer.Length << 1;
var newList = new T[newCapacity];
if (buffer != null && size > 0)
{
Array.ConstrainedCopy(buffer, 0, newList, 0, size);
}
buffer = newList;
}
}
public class BetterList<T>
{
#if UNITY_FLASH
List<T> mList = new List<T>();
/// <summary>
/// Direct access to the buffer. Note that you should not use its 'Length' parameter, but instead use BetterList.size.
/// </summary>
public T this[int i]
{
get { return mList[i]; }
set { mList[i] = value; }
}
/// <summary>
/// Compatibility with the non-flash syntax.
/// </summary>
public List<T> buffer { get { return mList; } }
/// <summary>
/// Direct access to the buffer's size. Note that it's only public for speed and efficiency. You shouldn't modify it.
/// </summary>
public int size { get { return mList.Count; } }
/// <summary>
/// For 'foreach' functionality.
/// </summary>
public IEnumerator<T> GetEnumerator () { return mList.GetEnumerator(); }
/// <summary>
/// Clear the array by resetting its size to zero. Note that the memory is not actually released.
/// </summary>
public void Clear () { mList.Clear(); }
/// <summary>
/// Clear the array and release the used memory.
/// </summary>
public void Release () { mList.Clear(); }
/// <summary>
/// Add the specified item to the end of the list.
/// </summary>
public void Add (T item) { mList.Add(item); }
/// <summary>
/// Insert an item at the specified index, pushing the entries back.
/// </summary>
public void Insert (int index, T item)
{
if (index > -1 && index < mList.Count) mList.Insert(index, item);
else mList.Add(item);
}
/// <summary>
/// Returns 'true' if the specified item is within the list.
/// </summary>
public bool Contains (T item) { return mList.Contains(item); }
/// <summary>
/// Return the index of the specified item.
/// </summary>
public int IndexOf (T item) { return mList.IndexOf(item); }
/// <summary>
/// Remove the specified item from the list. Note that RemoveAt() is faster and is advisable if you already know the index.
/// </summary>
public bool Remove (T item) { return mList.Remove(item); }
/// <summary>
/// Remove an item at the specified index.
/// </summary>
public void RemoveAt (int index) { mList.RemoveAt(index); }
/// <summary>
/// Remove an item from the end.
/// </summary>
public T Pop ()
{
if (buffer != null && size != 0)
{
T val = buffer[mList.Count - 1];
mList.RemoveAt(mList.Count - 1);
return val;
}
return default(T);
}
/// <summary>
/// Mimic List's ToArray() functionality, except that in this case the list is resized to match the current size.
/// </summary>
public T[] ToArray () { return mList.ToArray(); }
/// <summary>
/// List.Sort equivalent.
/// </summary>
public void Sort (System.Comparison<T> comparer) { mList.Sort(comparer); }
#else
/// <summary>
/// Direct access to the buffer. Note that you should not use its 'Length' parameter, but instead use BetterList.size.
/// </summary>
public T[] buffer;
/// <summary>
/// Direct access to the buffer's size. Note that it's only public for speed and efficiency. You shouldn't modify it.
/// </summary>
public int size = 0;
/// <summary>
/// For 'foreach' functionality.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public IEnumerator<T> GetEnumerator()
{
if (buffer != null)
{
for (int i = 0; i < size; ++i)
{
yield return buffer[i];
}
}
}
/// <summary>
/// Convenience function. I recommend using .buffer instead.
/// </summary>
[DebuggerHidden]
public T this[int i]
{
get { return buffer[i]; }
set { buffer[i] = value; }
}
public void Reserve(int capacity)
{
if (buffer == null || buffer.Length < capacity)
{
ResizeBuffer(true, capacity);
}
}
/// <summary>
/// Clear the array by resetting its size to zero. Note that the memory is not actually released.
/// </summary>
public void Clear() { size = 0; }
/// <summary>
/// Clear the array and release the used memory.
/// </summary>
public void Release() { size = 0; RecycleBuffer(buffer); buffer = null; }
/// <summary>
/// Add the specified item to the end of the list.
/// </summary>
public void Add(T item)
{
if (buffer == null || size == buffer.Length) ResizeBuffer(true);
buffer[size++] = item;
}
public void AddRange(T[] collection, int rangeCount)
{
InsertRange(size, collection, rangeCount);
}
/// <summary>
/// Insert an item at the specified index, pushing the entries back.
/// </summary>
public void Insert(int index, T item)
{
if (buffer == null || size == buffer.Length) ResizeBuffer(true);
if (index > -1 && index < size)
{
Array.ConstrainedCopy(buffer, index, buffer, index + 1, size - index);
buffer[index] = item;
++size;
}
else Add(item);
}
public void InsertRange(int index, T[] collection, int rangeCount)
{
InsertRange(index, 0, collection, rangeCount);
}
public void InsertRange(int index, int collectionStartIndex, T[] collection, int rangeCount)
{
if (collection == null)
{
return;
}
if ((uint)index > (uint)size || (uint)collectionStartIndex > (uint)size)
{
throw new ArgumentOutOfRangeException();
}
rangeCount = Mathf.Min(collection.Length, rangeCount);
if (rangeCount > 0)
{
if (buffer == null || buffer.Length < size + rangeCount)
{
ResizeBuffer(true, size + rangeCount);
}
if (index < size)
{
Array.ConstrainedCopy(buffer, index, buffer, index + rangeCount, size - index);
}
if (buffer == collection)
{
Array.ConstrainedCopy(buffer, collectionStartIndex, buffer, index, rangeCount);
}
else
{
Array.ConstrainedCopy(collection, collectionStartIndex, buffer, index, rangeCount);
}
size += rangeCount;
}
}
/// <summary>
/// Returns 'true' if the specified item is within the list.
/// </summary>
public bool Contains(T item)
{
if (buffer == null) return false;
EqualityComparer<T> c = EqualityComparer<T>.Default;
for (int i = 0; i < size; i++)
{
if (c.Equals(buffer[i], item)) return true;
}
return false;
}
/// <summary>
/// Return the index of the specified item.
/// </summary>
public int IndexOf(T item)
{
return Array.IndexOf(buffer, item, 0, size);
}
/// <summary>
/// Remove the specified item from the list. Note that RemoveAt() is faster and is advisable if you already know the index.
/// </summary>
public bool Remove(T item)
{
if (buffer != null)
{
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
return true;
}
return false;
}
return false;
}
/// <summary>
/// Remove an item at the specified index.
/// </summary>
public void RemoveAt(int index)
{
if (buffer != null && index > -1 && index < size)
{
--size;
Array.ConstrainedCopy(buffer, index + 1, buffer, index, size - index);
buffer[size] = default(T);
}
}
/// <summary>
/// Remove an item from the end.
/// </summary>
public T Pop()
{
if (buffer != null && size != 0)
{
T val = buffer[--size];
buffer[size] = default(T);
return val;
}
return default(T);
}
/// <summary>
/// Mimic List's ToArray() functionality, except that in this case the list is resized to match the current size.
/// </summary>
public T[] ToArray() { Trim(); return buffer; }
//class Comparer : System.Collections.IComparer
//{
// public System.Comparison<T> func;
// public int Compare (object x, object y) { return func((T)x, (T)y); }
//}
//Comparer mComp = new Comparer();
/// <summary>
/// List.Sort equivalent. Doing Array.Sort causes GC allocations.
/// </summary>
//public void Sort (System.Comparison<T> comparer)
//{
// if (size > 0)
// {
// mComp.func = comparer;
// System.Array.Sort(buffer, 0, size, mComp);
// }
//}
/// <summary>
/// List.Sort equivalent. Manual sorting causes no GC allocations.
/// </summary>
[DebuggerHidden]
[DebuggerStepThrough]
public void Sort(CompareFunc comparer)
{
int start = 0;
int max = size - 1;
bool changed = true;
while (changed)
{
changed = false;
for (int i = start; i < max; ++i)
{
// Compare the two values
if (comparer(buffer[i], buffer[i + 1]) > 0)
{
// Swap the values
T temp = buffer[i];
buffer[i] = buffer[i + 1];
buffer[i + 1] = temp;
changed = true;
}
else if (!changed)
{
// Nothing has changed -- we can start here next time
start = (i == 0) ? 0 : i - 1;
}
}
}
}
/// <summary>
/// Comparison function should return -1 if left is less than right, 1 if left is greater than right, and 0 if they match.
/// </summary>
public delegate int CompareFunc(T left, T right);
//~BetterList()
//{
// lock (SyncRoot)
// {
// RecycleBuffer(buffer);
// }
//}
/// <summary>
/// Helper function that resizes the size of the array, maintaining the content.
/// </summary>
private void ResizeBuffer(bool bExpand, int min = 1)
{
int minLength = min;
int desiredLength = min;
if (bExpand)
{
minLength = (buffer != null) ? Mathf.Max(buffer.Length + 1, 32) : 32;
minLength = Mathf.Max(minLength, min);
desiredLength = (buffer != null) ? Mathf.Max(buffer.Length << 1, 32) : 32;
if (desiredLength < min) desiredLength = (Mathf.Max(32, min) / 32) * 32 << 1;
}
T[] newList = null;
BufferPoolNode fondBufferNode = GetCachedBufferPoolNode(minLength, desiredLength, !bExpand);
bool bFond = fondBufferNode != null && fondBufferNode.bufferPool.Count > 0;
if (bFond)
{
LinkedListNode<T[]> firstNode = fondBufferNode.bufferPool.First;
newList = firstNode.Value;
fondBufferNode.bufferPool.RemoveFirst();
firstNode.Value = null;
_invalidNode.AddLast(firstNode);
}
else newList = new T[desiredLength];
if (buffer != null && size > 0)
{
Array.ConstrainedCopy(buffer, 0, newList, 0, size);
}
RecycleBuffer(buffer);
buffer = newList;
}
/// Trim the unnecessary memory, resizing the buffer to be of 'Length' size.
/// Call this function only if you are sure that the buffer won't need to resize anytime soon.
/// </summary>
private void Trim()
{
if (size > 0)
{
if (size < buffer.Length)
{
ResizeBuffer(false, size);
}
}
else
{
RecycleBuffer(buffer);
buffer = null;
}
}
private void RecycleBuffer(T[] dirtyBuffer)
{
if (dirtyBuffer == null)
return;
BufferPoolNode fondBufferNode = GetCachedBufferPoolNode(dirtyBuffer.Length, dirtyBuffer.Length, true);
AppendBufferNode(fondBufferNode.bufferPool, dirtyBuffer);
}
//object SyncRoot
//{
// get
// {
// if (_syncRoot == null)
// {
// System.Threading.Interlocked.CompareExchange<System.Object>(ref _syncRoot, new System.Object(), null);
// }
// return _syncRoot;
// }
//}
private BufferPoolNode GetCachedBufferPoolNode(int minLength, int desiredLength, bool bStrictLength)
{
CleanOldBuffer();
int bufferLen = _bufferMap.Count();
BufferPoolNode fondBufferNode = null;
if (bufferLen > 0)
{
cachedSerchNode.bufferLength = minLength;
int index = Array.BinarySearch(_bufferMap.buffer, 0, bufferLen, cachedSerchNode, poolCompare);
int realIndex = index >= 0 ? index : ~index;
if (realIndex < bufferLen && !bStrictLength)
{
int len = bufferLen - 1;
BufferPoolNode tempNode = null;
do
{
tempNode = _bufferMap.buffer[realIndex];
}
while (tempNode.bufferPool.Count == 0 && realIndex++ < len);
}
bool bNodeAvailable = realIndex < bufferLen;
bNodeAvailable &= bStrictLength ? index >= 0 : bNodeAvailable;
if (bNodeAvailable)
{
fondBufferNode = _bufferMap.buffer[realIndex];
}
}
if (fondBufferNode == null)
{
cachedSerchNode.bufferLength = desiredLength;
int index = 0;
if (bufferLen > 0)
{
index = Array.BinarySearch(_bufferMap.buffer, 0, bufferLen, cachedSerchNode, poolCompare);
}
int realIndex = index >= 0 ? index : ~index;
if (index >= 0 && bufferLen > 0)
{
fondBufferNode = _bufferMap.buffer[realIndex];
}
else if (realIndex < bufferLen)
{
fondBufferNode = CreateNewNode(desiredLength);
_bufferMap.Insert(realIndex, fondBufferNode);
}
else
{
fondBufferNode = CreateNewNode(desiredLength);
_bufferMap.Add(fondBufferNode);
}
}
fondBufferNode.lastUsedFrame = Time.frameCount;
return fondBufferNode;
}
private void AppendBufferNode(LinkedList<T[]> bufferPool, T[] recyclingBuffer)
{
LinkedListNode<T[]> newNode = null;
if (_invalidNode.Count > 0)
{
newNode = _invalidNode.Last;
_invalidNode.RemoveLast();
newNode.Value = recyclingBuffer;
}
if (newNode != null)
bufferPool.AddLast(newNode);
else
bufferPool.AddLast(recyclingBuffer);
}
static private BufferPoolNode CreateNewNode(int bufferLen)
{
return new BufferPoolNode()
{
bufferLength = bufferLen,
lastUsedFrame = Time.frameCount,
bufferPool = new LinkedList<T[]>()
};
}
static private bool IsPowerOfTwo(int n)
{
return /*(n > 0) && */(n & (n - 1)) == 0;
}
static private void CleanOldBuffer()
{
int bufferLen = _bufferMap.Count();
if (Time.frameCount == lastCleanFrame || bufferLen == 0)
{
return;
}
lastCleanFrame = Time.frameCount;
if (collectIndex >= bufferLen)
{
collectIndex = 0;
}
var node = _bufferMap.buffer[collectIndex++];
if (!IsPowerOfTwo(node.bufferLength) && Time.frameCount - node.lastUsedFrame >= collectCondition)
{
node.lastUsedFrame = Time.frameCount;
node.bufferPool.Clear();
}
}
//static private object _syncRoot;
static private int collectIndex;
static private int lastCleanFrame;
static private int collectCondition = 12000;
static private BufferPoolNode cachedSerchNode = new BufferPoolNode();
static private PoolNodeCompare poolCompare = new PoolNodeCompare();
static private LinkedList<T[]> _invalidNode = new LinkedList<T[]>();
static private BufferPoolNodeList<BufferPoolNode> _bufferMap = new BufferPoolNodeList<BufferPoolNode>();
private class PoolNodeCompare : IComparer<BufferPoolNode>
{
public int Compare(BufferPoolNode x, BufferPoolNode y)
{
return x.bufferLength - y.bufferLength;
}
}
private class BufferPoolNode
{
public int bufferLength = 0;
public int lastUsedFrame = 0;
public LinkedList<T[]> bufferPool = new LinkedList<T[]>();
}
#endif
}