2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# Enumの文字列変換は重い

Posted at

EnumをToStringすると激重なので、事前にswitch文やarrayで文字列を定義しておくと、パフォーマンスを上げることができる

コード

[RankColumn]
public class EnumTest
{
	[Params(Weapon.WeaponType.A)]
	public Weapon.WeaponType weaponType;

	[Benchmark]
	public string Case1()
	{
		return weaponType.GetNameSwitch();
	}

	[Benchmark]
	public string Case2()
	{
		return weaponType.GetNameArray();
	}

	[Benchmark]
	public string Case3()
	{
		return weaponType.GetNameToString();
	}
}

public static class Weapon
{
	public enum WeaponType
	{
		A,
		B,
		C,
	}

	private static string[] weaponTypeArray = {
		"A",
		"B",
		"C",
	};

	public static string GetNameSwitch(this WeaponType type)
	{
		switch (type)
		{
			case WeaponType.A: return "A";
			case WeaponType.B: return "B";
			case WeaponType.C: return "C";
		}
		throw new NotImplementedException();
	}

	public static string GetNameArray(this WeaponType type)
	{
		return weaponTypeArray[(int)type];
	}

	public static string GetNameToString(this WeaponType type)
	{
		return type.ToString();
	}
}

結果

//BenchmarkDotNet=v0.12.0, OS=Windows 10.0.18362
//Intel Core i5-9600K CPU 3.70GHz(Coffee Lake), 1 CPU, 6 logical and 6 physical cores
// [Host]     : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT
//  DefaultJob : .NET Framework 4.8 (4.8.4121.0), X64 RyuJIT

//| Method | weaponType |        Mean |     Error |    StdDev | Rank |
//|------- |----------- |------------:|----------:|----------:|-----:|
//|  Case1 |          A |   1.2287 ns | 0.0263 ns | 0.0246 ns |    2 |
//|  Case2 |          A |   0.0523 ns | 0.0123 ns | 0.0115 ns |    1 |
//|  Case3 |          A | 282.2946 ns | 1.4594 ns | 1.3652 ns |    3 |
2
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?