我用 c++ 编写了自己的 Array 类,并重载了数组下标 [] 运算符,代码:
inline dtype &operator[](const size_t i) { return _data[i]; }
inline dtype operator[](const size_t i) const { return _data[i];}
其中_data是指向包含数组的内存块的指针。分析表明,仅此重载运算符就占用了大约 10% 的总计算时间(在长时间的蒙特卡罗模拟中,我正在使用具有最大优化的 g++ 进行编译)。这似乎很多,知道这是为什么吗?
编辑:dtype 是双精度,_data 是指向双精度数组的指针
operator[]
的const
重载实际上是返回副本而不是dtype const &
。如果 dtype 很大,则副本可能很昂贵。
像这样进行原型设计应该可以解决这个问题:
inline dtype const & operator[] (const size_t i) const { return _data[i]; }