简体   繁体   中英

Any performance penalty for wrapping int in a class?

I have a project with many vectors, sets and maps. In most cases the key/index is an integer. I am considering creating small classes like:

class PhoneRepoIx //index into map {phone_number => pointer}
{
public:
  int n;
};

class PersonIx //index into map {social_security_number => pointer}
{
public:
  int n;
};

Would I incur any speed or memory penalty? With memory I am 90% sure that there would be no memory cost per instance, only per class-type. With speed I am not clear.

Motivation: With the above approach, the compiler would do some extra type-checking for me. Also, with well chosen explicit type-names, the reader of my code will see more easily what I am doing. As of now I am using int everywhere and I chose the variable names to express what each index is. With the above, my variable names could be shorter.

Note: Tyepdefs do not address my issue completely as the compiler would not do any extra type-checking, internally all the types would just be int.

Different compilers have different optimization abilities and different bugs. It is theoretically possible to compile this with precisely zero overhead. Will your compiler attain this theoretical limit? The answer is a definite "maybe". At least some compilers are known to do it at least some of the time.

The more interesting question is whether you should be worried over a possible performance degradation. And the answer to this question is a strong "no". Not until your program does in fact show unacceptable performance figures.

I would suggest the use of templates to get what you want.

template <typename T>
struct Index {
    Index(int value) : value(value) {}
    int value;
};

This is used like.

struct PhoneRepoIx {};
Index<PhoneRepoIx> PhoneIndex(1);
list[PhoneIndex.value];

There are two functions which will commonly be called on this class:

  • Constructor
  • operator< (since STL map is a tree impl, the keys should support this)

I think the above answer "don't worry" sounds pretty good (profile then optimize). But to take a crack at why this won't cause any slowdown (guesswork):

  • Constructor: No reason why a decent compiler couldn't turn this into a stack pointer increment (to make space for the int) followed by setting the available space.
  • operator<: No reason why a decent compiler couldn't inline the simple comparison between the 'n's of the two objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM