如何优化C ++代码? [英] How to optimize C++ code?
本文介绍了如何优化C ++代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为了便于说明,我的数据结构如下所示。什么是最快的代码1或代码2?
struct 数组{
// 数组长度
public : int length;
// 指向int数组的指针
public : int * pData;
// 分配数组
public : bool allocate( int size);
// 构造函数
public :Array( int size){
allocate(size);
}
// 默认构造函数
< span class =code-keyword> public :Array(){
length = 0 ;
pData = 0 ;
}
public :~Array(){
if (pData) delete [] pData;
}
};
代码1:
< pre lang =c ++> Array array ( 10000 );
for ( int i = 0 ; i< array .length; i ++) array .pData [i] = i * 2 ;
代码2:
数组数组( 10000 );
int l = array .length;
int * pData = array .pData;
for ( int i = 0 ; i< l; i ++)pData [i] = i * 2 ;
解决方案
如前所述,如果有疑问,请让编译器为您生成汇编代码,然后比较它们。使用一个不错的编译器应该没有区别。
你可以尝试编写C ++并使用std :: vector
和的std ::产生()
。只有这样太慢才考虑自己管理内存。即使您需要自己管理内存,也可以使用std :: unique_ptr
自动排序释放内存。
在发布版本中两种解决方案应该具有相同的速度,因为优化。
代码3:
数组数组( 10000 );
int l = array.length;
int * pData = array.pData;
for ( int i = 0 ; i < l; i ++)pData ++ = i * 2;
抵消了被访问的数组pData ++
: - )
For illustration purposes, I have a data structure as shown below. What is the fastest Code 1 or Code 2?
struct Array{
// length of array
public: int length;
// pointer to int array
public: int *pData;
// allocate array
public: bool allocate(int size);
// constructor
public: Array(int size){
allocate(size);
}
// default constructor
public: Array(){
length = 0;
pData = 0;
}
public: ~Array(){
if(pData) delete []pData;
}
};
Code 1:
Array array(10000);
for(int i = 0;i < array.length;i++) array.pData[i] = i*2;
Code 2:
Array array(10000);
int l = array.length;
int *pData = array.pData;
for(int i = 0;i < l;i++) pData[i] = i*2;
解决方案
As already suggested, if in doubt, make the compiler generate the assembly codes for you and then compare them. With a decent compiler there should be no difference.
You could try writing C++ and usestd::vector
andstd::generate()
. Only if that's too slow consider managing memory yourself. Even if you need to manage memory yourself then usestd::unique_ptr
to automagically sort out releasing the memory.
in a release build both solution should have the same speed, because optimization.
Code 3:
Array array(10000); int l = array.length; int *pData = array.pData; for(int i = 0;i < l;i++) pData++ = i*2;
with offsetting the accessed arraypData++
:-)
这篇关于如何优化C ++代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文