The only answer is to use struct
Don't try to be smarter than compiler. Don't perform premature optimization. Write simplest and clearest code and only after you see it too slow, perform low-level optimization
Struct are better here because:
- It is portable
- It safe
- It is c++ ideomatic.
- It is faster.
Let me bust your myths about comparing speed of long long and struct. As you know, all ways to optimize your code starts with profiling. Lets make simple program and measure comparing speed of vectors of long long
and struct S
:
#include <iostream>
#include <string>
#include <vector>
#include <windows.h>
struct S
{
unsigned int a;
void* b;
bool operator==(const S& other) const
{
return a == other.a && b == other.b;
}
};
template <typename Iterator>
int count_eq(Iterator begin, Iterator end)
{
int result = 0;
for (Iterator i = begin; i != end; ++i) {
for (Iterator j = i + 1; j != end; ++j) {
result += *i == *j;
}
}
return result;
}
template <typename Iterator>
void mesure(Iterator begin, Iterator end)
{
long long t0 = GetTickCount();
int res = count_eq(begin, end);
long long t1 = GetTickCount();
std::cout << "result: " << res <<"; Time: "<<(t1-t0)<<"\n";
}
int main()
{
const unsigned int Size = 20000;
std::vector<unsigned long long> l;
for (int i = 0; i < Size; i++) {
l.push_back(i% (Size/10));
}
std::vector<S> s;
for (int j = 0; j < Size; j++) {
S el;
el.a = j% (Size/10);
el.b = 0;
s.push_back(el);
}
mesure(l.begin(), l.end());
mesure(s.begin(), s.end());
}
Lets check results:
>g++ src.cpp -O3
>a
result: 90000; Time: 327
result: 90000; Time: 188
Yes, struct
with custom operator ==
1.5 times faster.