473,668 Members | 2,491 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

switch is not optimized for mapping between enums

Hello,
I have used some library where is defined enum like:

typedef enum Enum1 { ENUM1_1, ENUM1_2, ENUM1_3, ENUM1_4, ENUM1_5 };

In my code I have defined:

typedef enum Enum2 { ENUM2_1, ENUM2_2, ENUM2_3, ENUM2_4, ENUM2_5 };

My map function looks like:

Enum2 mapEnum1toEnum2 ( Enum1 enum )
{
switch( enum )
{
case ENUM1_1: return ENUM2_1;
case ENUM1_2: return ENUM2_2;
case ENUM1_3: return ENUM2_3;
case ENUM1_4: return ENUM2_4;
case ENUM1_5: return ENUM2_5;
default: throw "UNKNOWN ENUM1!!!";
}
}

I have analised asm code generated by compiler, and the results is not
optimal as it can be. Because the enums can map 1:1 I have expected that
compiler creates code similar to:

Enum2 mapEnum1toEnum2 ( Enum1 enum )
{
if ( enum < ENUM1_1 || enum ENUM1_5 )
throw "UNKNOWN ENUM1!!!";
return reinterpret_cas t<Enum2>( enum );
}

In example above both enums are continuous, but in case if one of enums
is not continuous there is another possibility - create hash table e.g.
typedef enum Enum2 { ENUM2_1 = -1, ENUM2_2 = 33, ENUM2_3 = 55, ENUM2_4 =
1234, ENUM2_5 = 5533 };

Enum2 mapEnum1toEnum2 ( Enum1 enum )
{
static const Enum2 hash[] = { ENUM2_1, ENUM2_2, ENUM2_3, ENUM2_4,
ENUM2_5 };
if ( enum < ENUM1_1 || enum ENUM1_5 )
throw "UNKNOWN ENUM1!!!";
return hash[enum];
}
Do you know any implementation to create mapEnum1toEnum2 function which
is better optimized than switch construction. Maybe there is possible
to use metaprogramming for this issue.

Best Regards
MariuszC

Nov 11 '06 #1
3 2217
MariuszC wrote:

You don't have to ask twice.
Hello,
I have used some library where is defined enum like:

typedef enum Enum1 { ENUM1_1, ENUM1_2, ENUM1_3, ENUM1_4, ENUM1_5 };

In my code I have defined:

typedef enum Enum2 { ENUM2_1, ENUM2_2, ENUM2_3, ENUM2_4, ENUM2_5 };

My map function looks like:

Enum2 mapEnum1toEnum2 ( Enum1 enum )
{
switch( enum )
{
case ENUM1_1: return ENUM2_1;
case ENUM1_2: return ENUM2_2;
case ENUM1_3: return ENUM2_3;
case ENUM1_4: return ENUM2_4;
case ENUM1_5: return ENUM2_5;
default: throw "UNKNOWN ENUM1!!!";
}
}

I have analised asm code generated by compiler, and the results is not
optimal as it can be. Because the enums can map 1:1 I have expected that
compiler creates code similar to:
Is this a problem to your application?

If the list is quite long and a switch is inefficient, you could try a
std::map<Enum1, Enum2>.

The only way to tell which is better is to profile your application.

--
Ian Collins.
Nov 11 '06 #2
Ian Collins wrote:
MariuszC wrote:
....
>I have analised asm code generated by compiler, and the results is not
optimal as it can be. Because the enums can map 1:1 I have expected that
compiler creates code similar to:
Is this a problem to your application?

If the list is quite long and a switch is inefficient, you could try a
std::map<Enum1, Enum2>.

The only way to tell which is better is to profile your application.

std::map is way more expensive than a switch.

Perhaps you could do something like this.
enum OldEnum
{
OA=1,
OB,
OC
};

enum {
g_smallest_old = OA,
g_largest_old = OC
};

enum NewEnum
{
NA=10,
NB,
NC,
BAD=-1
};
template <int w_enum>
struct OldEnumMap
{
static const NewEnum m_value = BAD;
};
template <NewEnum w_enum>
struct NewEnumMap
{
static const NewEnum m_value = w_enum;
};

// define the mapping between old and new enums
template <struct OldEnumMap<OA: NewEnumMap<NA{} ;
template <struct OldEnumMap<OB: NewEnumMap<NB{} ;
template <struct OldEnumMap<OC: NewEnumMap<NC{} ;

NewEnum enummap[] = {
OldEnumMap<0>:: m_value,
OldEnumMap<1>:: m_value,
OldEnumMap<2>:: m_value,
OldEnumMap<3>:: m_value,
OldEnumMap<4>:: m_value,
// ... fill in to your heart's content
};

NewEnum Convert( OldEnum i_val )
{
if ( i_val < int(g_smallest_ old) )
{
return BAD;
}

if ( i_val int(g_largest_o ld) )
{
return BAD;
}

return enummap[ i_val ];
}

#include <iostream>
int main()
{
// dynamic conversion
std::cout << Convert(OB) << "\n";

// static (compile time) conversion
std::cout << OldEnumMap<OB>: :m_value << "\n";

}
Nov 11 '06 #3


Ian Collins wrote:
MariuszC wrote:

You don't have to ask twice.
In first version I made mistake in condition, there was && instead of
||. I was deleting first post before sending second corrected one.

Mariusz
Nov 11 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2603
by: Rudi Hansen | last post by:
I dont seem to be able to find the switch statement in Python. I would like to be able to do switch(var) case 1 : print "var = 1" case 2: print "var = 2"
6
6526
by: naruto | last post by:
Hi all, I have the following being defined in a A.cxx file. // define in source file. Not exported to the outside world (this cannot be // moved to the header file ) #define CHANNEL_0 0 #define CHANNEL_1 1 #define CHANNEL_2 2
24
3158
by: | last post by:
Hi, I need to read a big CSV file, where different fields should be converted to different types, such as int, double, datetime, SqlMoney, etc. I have an array, which describes the fields and their types. I would like to somehow store a reference to parsing operations in this array (such as Int32.Parse, Double.Parse, SqlMoney.Parse, etc), so I can invoke the appropriate one without writing a long switch.
65
6666
by: He Shiming | last post by:
Hi, I just wrote a function that has over 200 "cases" wrapped in a "switch" statement. I'm wondering if there are performance issues in such implementation. Do I need to optimize it some way? In terms of generated machine code, how does hundreds of cases in a switch differ from hundreds of if-elses? Do compilers or processors do any optimization on such structured code? Do I need to worry about the performance, usually?
10
1483
by: cody | last post by:
Why can't we use switches with singleton objects? I know that the compiler cannot optimize them like constant values but the same is true for strings and they are allowed in switches. The reason is that I often use singleton classes as replacement for enum's because enums does'nt provide me a (localizeable) names or descriptions when I for example fill comboboxes with them. Additionally I don't like that I can't put any code in the...
9
1388
by: cody | last post by:
Why can't switch used for objects, at least for static readonly fields it wold be nice. The Jit could certainly optimize this case because the addresses of static readonly variables are known at jit time. The thing is that is often used my own enum classes because I usually want to assign a userfriendly (and localizable) name to an enum member which is automatically displayed if I add a enum member to a combobox for example....
1
284
by: MariuszC | last post by:
Hello, I have used some library where is defined enum like: typedef enum Enum1 { ENUM1_1, ENUM1_2, ENUM1_3, ENUM1_4, ENUM1_5 }; In my code I have defined: typedef enum Enum2 { ENUM2_1, ENUM2_2, ENUM2_3, ENUM2_4, ENUM2_5 }; My map function looks like:
11
10855
by: Peter Kirk | last post by:
Hi i have a string variable which can take one of a set of many values. Depending on the value I need to take different (but related) actions. So I have a big if/else-if construct - but what is a better way of doing this? if ("control" == commandString) { } else if ("execute" == commandString)
12
12318
by: | last post by:
Is it fine to call another method from Switch? Eg. Switch (stringVar) { case ("a"): somVar = "whatever"; Another_Method(); //call another method return;
7
5256
by: Kurt | last post by:
Hi. I have a c++ project that is basically a set of implementation hiding classes, so that we can convert a static lib with a lot of dependancies into a dynamic lib with less dependancies, so that users of the lib dont require all the development tools we used to develop the lib. I have noticed something strange, and was wondering if its a C++ feature, or a implementation specific bug. I have a function like this:
0
8381
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8893
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8586
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7401
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5681
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4205
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4380
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2792
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1786
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.