Created
June 18, 2021 10:49
-
-
Save Isshi-777/a02a11200137cc2f008607548080665a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
using UnityEngine; | |
/// <summary> | |
/// ビットフラグの速度チェックテストコード(Unity2020.3.11f) | |
/// </summary> | |
public class EnumFlagCheck : MonoBehaviour | |
{ | |
[Flags] | |
private enum Flag | |
{ | |
None = 0, | |
A = 1 << 0, | |
B = 1 << 1, | |
C = 1 << 2, | |
D = 1 << 3, | |
E = 1 << 4, | |
} | |
private Flag flag = Flag.None; | |
private int flagInt = 0; | |
private void Start() | |
{ | |
Initialize(); | |
for (int i = 0; i < 3; i++) | |
{ | |
Sample(); | |
} | |
} | |
private void Initialize() | |
{ | |
// 適当にフラグをセット | |
Flag[] list = new Flag[] { Flag.A, Flag.B, Flag.C, Flag.D, Flag.E }; | |
for (int i = 0; i < 100; i++) | |
{ | |
int index = UnityEngine.Random.Range(0, list.Length); | |
bool isOn = UnityEngine.Random.Range(0, 2) == 1; | |
SetFlag(list[index], isOn); | |
} | |
} | |
private void Sample() | |
{ | |
int count = 10000000; //1千万ループ | |
Stopwatch sw = new Stopwatch(); | |
// HasFlag | |
sw.Start(); | |
for (int i = 0; i < count; i++) | |
{ | |
bool val = GetFlag(Flag.D); | |
} | |
sw.Stop(); | |
UnityEngine.Debug.Log(" HasFlag : " + sw.ElapsedMilliseconds); | |
sw.Reset(); | |
// Int | |
sw.Start(); | |
for (int i = 0; i < count; i++) | |
{ | |
bool val = GetFlagInt(Flag.D); | |
} | |
sw.Stop(); | |
UnityEngine.Debug.Log(" FlagInt : " + sw.ElapsedMilliseconds); | |
} | |
private void SetFlag(Flag f, bool isOn) | |
{ | |
if (isOn) | |
{ | |
flag |= f; | |
flagInt |= (int)f; | |
} | |
else | |
{ | |
flag &= ~f; | |
flagInt &= (int)~f; | |
} | |
} | |
private bool GetFlag(Flag f) | |
{ | |
return flag.HasFlag(f); | |
} | |
private bool GetFlagInt(Flag f) | |
{ | |
return (flagInt & (int)f) != 0; | |
} | |
} | |
/* | |
* 計3ループ | |
* ●1回目 | |
* GetFlag : 1744ms | |
* GetFlagInt : 5ms | |
* | |
* ●2回目 | |
* GetFlag : 1708ms | |
* GetFlagInt : 5ms | |
* | |
* ●3回目 | |
* GetFlag : 1711ms | |
* GetFlagInt : 5ms | |
* | |
* 参考 | |
* https://qiita.com/stc1988/items/e6f76503ddf06fcf20b8 | |
* https://note.dokeep.jp/post/csharp-enum-flags/ | |
* https://ufcpp.net/study/csharp/oop/miscimplictinherit/ | |
* etc... | |
* | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment