We also talk about using reflection to implement Enum → string ing: a method that focuses on performance)

Source: Internet
Author: User

I. Question proposal

Recently, many blogger in the blog Park proposed to display Chinese names for enumeration.ArticleFor example, [display Chinese information for enumeration members], [use custom attributes to define detailed texts of enumeration values], [Details determine success or failure: ing enumeration], [using descriptionattribute to define the description of enumeration values], there are some articles I have read (sorry, I am not sure about the address ). The common feature of these articles is that a custom attribute is used to append an enumeration value to obtain enumeration-related information at runtime.

In this method, reflection is used, because some people are concerned about the performance problems, especially when processing a large amount of data, such as importing a large number of enumerations into the DataGrid. People also find that, the tostring method of Enum also uses the reflection method, so there is actually a slow speed problem. This article tries to focus on performance. Based on the experience of the experts above, we will give a method that focuses on performance without losing the structure's accessibility and scalability.

Design goals:

1. The enumeration definition form uses an additional attribute that is easy to read and write;
2. Supports multi-language versions and can be easily localized;
3. The call format is simple.

Ii. tostring () performance problems
For an enumerated value emitem, use the followingCodeTest:
For (INT I = 0; I <1000000; I ++)
{
S = emitem. tostring ();
}

Here, S is a string type, and emitem is an enumeration of the myenum type.
On my machine, this cycle takes about 4900 milliseconds.

After I Replace "s = emitem. tostring ();" with "S = enum. getname (typeof (myenum), emitem);", this time is reduced to 2300 milliseconds.

However, it must be noted that the tostring method and the getname method are not the same, but sometimes we can use either of them.
Therefore, my first suggestion is to use getname instead of tostring if they can be exchanged.

Iii. Reflection performance problems
Obviously, the preceding two methods tostring and getname cannot solve the problem of displaying enumeration User-Defined names and providing different language versions. Therefore, many people adopt the reflection method, as shown in the following example, adding attribute for each enumerated value:
Public Enum myenum
{
[Enumitemdescription ("description1")]
Enumvalue1 = 1,
[Enumitemdescription ("description2")]
Enumvalue2 = 2,
[Enumitemdescription ("description3")]
Enumvalue3 = 4,
}
Here, enumitemdescriptionattribute is a class similar to descriptionattribute.
This is indeed very elegant. when reading the value of this attribute, most of them use the following format:
Static string getstringfromenum (Enum enumvalue)
{
Fieldinfo finfo = enumvalue. GetType (). getfield (enumvalue. tostring ());
Object [] cattr = finfo. getcustomattributes (typeof (enumitemdescriptionattribute), true );
If (cattr. length> 0)
{
Enumitemdescriptionattribute DESC = cattr [0] As enumitemdescriptionattribute;
If (DESC! = NULL)
{
Return DESC. description;
}
}
Return enumvalue. tostring ();
}
In fact, this is a simplified model-it does not have a loop. In fact, many of the blogger's Program And compare the names of all fieldinfo, and then cycle each attribute of each fieldinfo-that is, the complexity is O (n ^ 2 ).

So what is the result when we use "s = getstringfromenum (emitem);" for our first experiment?

As a result, when I waited for 30 seconds, I finally got impatient. When I tried to forcibly close it, it ended up in 32 seconds, that is, 30 thousand 2 ms.

Think about it, it is slow, of course. Every time you map an enumerated value to a string, you must call it through reflection and call Enum every time. tostring, this slow guy!

Iv. dictionay + reflection cache implementation Attempt
Let's look back and think about why we must or prefer reflection here?
If reflection is not needed, we must write a ing function like the following:
Static string stringfromenum (myenum enumvalue)
{
Switch (enumvalue)
{
Case myenum. enumvalue1:
Return "string1 ";
Case myenum. enumvalue2:
Return "string2 ";
Case myenum. enumvalue3:
Return "string3 ";
}
Return enumvalue. tostring ();
}
(Or we can use a dictionary <myenum, string> for maintenance)

That is to say, the "enumeration value" and "enumeration Value Name" are separated. From the design point of view, this makes it difficult for future maintenance; however, this process is indeed fast.

So if we combine the two, isn't it perfect? First, read all the attributes with reflection, and store them in a list for backup. In the future, we will not call reflection for every call, but query this list (which is equivalent to cache? The procedure is as follows:

Public class enummap
{
Private type internalenumtype;
Private dictionary <Enum, string> map;

Public enummap (type enumtype)
{
If (! Enumtype. issubclassof (typeof (Enum )))
{
Throw new invalidcastexception ();
}
Internalenumtype = enumtype;
Fieldinfo [] staticfiles = enumtype. getfields (bindingflags. Public | bindingflags. Static );

Map = new dictionary <Enum, string> (staticfiles. Length );

For (INT I = 0; I <staticfiles. length; I ++)
{
If (staticfiles [I]. fieldtype = enumtype)
{
String description = "";
Object [] attrs = staticfiles [I]. getcustomattributes (typeof (enumitemdescriptionattribute), true );
Description = attrs. length> 0?
(Enumitemdescriptionattribute) attrs [0]). Description:
// If the enumitemdescription mark is not found, use the name of the enumerated value.
Description = staticfiles [I]. Name;

Map. Add (Enum) staticfiles [I]. getvalue (enumtype), description );
}
}
}

Public String This [Enum item]
{
Get
{
If (item. GetType ()! = Internalenumtype)
{
Throw new argumentexception ();
}
Return map [item];
}
}
}

In this way, we only need to create an instance of this type:
Enummap myenummap = new enummap (typeof (myenum ));
Then, call the following code in any place where the enumerated value needs to be mapped to a string:
S = myenummap [emitem];
You can.

So what is the result of the initial test using "s = myenummap [emitem?
The result is 650 milliseconds-it is one of the 50 minutes that are consumed without "Caching.

It is noted that the direct provision of the enummap class may cause several problems, and for each Enumeration type, we need to create an enummap object for it, which is troublesome;
Therefore, we perform the following simple encapsulation for it. On the one hand, we ensure its Singleton feature, and on the other hand, we do not need to create enummap objects one by one.
View the complete code of this class
Public class enummaphelper
{
// Maps is used to save each enumeration and its corresponding enummap object.
Private Static dictionary <type, enummap> maps;

// Because C # does not have the concept of static indexer, we use the static method here.
Public static string getstringfromenum (Enum item)
{
If (maps = NULL)
{
Maps = new dictionary <type, enummap> ();
}

Type enumtype = item. GetType ();

Enummap mapper = NULL;
If (maps. containskey (enumtype ))
{
Mapper = maps [enumtype];
}
Else
{
Mapper = new enummap (enumtype );
Maps. Add (enumtype, Mapper );
}
Return mapper [item];
}

Private class enummap
{
Private type internalenumtype;
Private dictionary <Enum, string> map;

Public enummap (type enumtype)
{< br> If (! Enumtype. issubclassof (typeof (Enum)
{< br> throw new invalidcastexception ();
}< br> internalenumtype = enumtype;
fieldinfo [] staticfiles = enumtype. getfields (bindingflags. public | bindingflags. static);

Map = new dictionary <Enum, string> (staticfiles. Length );

For (INT I = 0; I <staticfiles. length; I ++)
{
If (staticfiles [I]. fieldtype = enumtype)
{
String description = "";
Object [] attrs = staticfiles [I]. getcustomattributes (typeof (enumitemdescriptionattribute), true );
Description = attrs. length> 0?
(Enumitemdescriptionattribute) attrs [0]). Description:
// If the enumitemdescription mark is not found, use the name of the enumerated value.
Description = staticfiles [I]. Name;

Map. Add (Enum) staticfiles [I]. getvalue (enumtype), description );
}
}
}

Public String This [Enum item]
{
Get
{
If (item. GetType ()! = Internalenumtype)
{
Throw new argumentexception ();
}
Return map [item];
}
}
}
}
The calling method is simple. You only need one statement:
S = enummaphelper. getstringfromenum (emitem );

V. multi-language support
In terms of multi-language support, we only need to draw images like FCL:
Public class enumitemdescriptionattribute: descriptionattribute
{
Private bool replaced;

Public enumitemdescriptionattribute (string description)
: Base (description)
{
}
Public override string description
{
Get
{
If (! This. Replaced)
{
This. Replaced = true;
Base. descriptionvalue = Sr. getstring (base. Description );
}
Return base. description;
}
}
}
The SR is the class for synchronously reading resources, which has little to do with the content. Here we will skip it (refer to the implementation of FCL's SR ).

So far, a fast (four times faster than the tostring method of Enum itself), concise form (whether in declaration form or call form), supports multi-language ing Class is complete.
There may be several bugs and few exceptions are taken into consideration. You are welcome to give comments and suggestions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.