是的,就速度和内存而言,你是对的。
指针几乎总是占用比标准int 更多的字节,尤其是bool 和char 数据类型。在现代机器上,指针通常是 8 个字节,而 char几乎总是只有 1 个字节。
在本例中,从Foo 访问char 和bool 比从Bar 访问需要更多的机器指令:
struct Foo
{
char * c; // single character
bool * b; // single bool
};
struct Bar
{
char c;
bool b;
};
...如果我们决定创建一些数组,那么Foo 的数组大小将大 8 倍 - 并且代码更加分散,因此这意味着您最终将拥有很多更多缓存未命中。
#include <vector>
int main()
{
int size = 1000000;
std::vector<Foo> foo(size);
std::vector<Bar> bar(size);
return 0;
}
正如 dmckee 所指出的,单字节 bool 的单个副本和指针的单个副本一样快:
bool num1, num2,* p1, * p2;
num1 = num2; // this takes one clock cycle
p1 = p2; // this takes another
正如 dmckee 所说,当您使用 64 位架构时确实如此。
但是,ints、bools 和 chars 数组的复制会快得多,因为我们可以将它们的倍数压缩到每个寄存器中:
#include <iostream>
int main ()
{
const int n_elements = 100000 * sizeof(int64_t);
bool A[n_elements];
bool B[n_elements];
int64_t * A_fast = (int64_t *) A;
int64_t * B_fast = (int64_t *) B;
const int n_quick_elements = n_elements / sizeof(int64_t);
for (int i = 0; i < 10000; ++i)
for (int j = 0; j < n_quick_elements; ++j)
A_fast[j] = B_fast[j];
return 0;
}
使用type_traits (is_trivially_copyable) 和std::memcopy,STL 容器和其他优秀的库为我们做这种事情。假装指针总是一样快,会阻碍这些库的优化。
结论:这些示例看起来很明显,但仅当您需要获取/授予对原始对象的访问权限时,才对基本数据类型使用指针/引用。