Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any performance penalty for wrapping int in a class?

Tags:

c++

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.

like image 332
Radim Cernej Avatar asked Jul 19 '12 19:07

Radim Cernej


1 Answers

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.

like image 76
n. 1.8e9-where's-my-share m. Avatar answered Sep 18 '22 05:09

n. 1.8e9-where's-my-share m.