今天的项目进展顺利,跟踪程序发现项目中对文件读取的函数调用的是一个继承自VECTOR类的operator [] ,通过自觉认为模板确实具有很好的通用性,但如果把只需要实现一些简单功能的类继承于VECTOR,那么类不但从空间上会有很大开销,效率也一定会有所下降.于是自己编写了一个可变长的数组类, 通过PROFILE,发现性能的确有了可观的提高!所以在我们选择标准库的时候 一定要考虑是否有必要自己写一个模拟类来实现从而提高性能与空间上的效率,尤其是在针对一个已知类型的时候.
下面是没模拟的时候的代码
class charVector:public std::vector<char>
{
public:
#define BLOCKSZ 128
typedef std::vector<char> t_parent;
charVector()
{
assign(BLOCKSZ, 0);
}
value_type& operator[](const int& idx)
{
if(idx >= size())
{
resize(idx+BLOCKSZ);
}
return t_parent ::operator[](idx);
}
};
下面是我模拟后的代码
//*************************************************
//This calss is created for instead of charvector *
//*************************************************
class charbox
{
static const int array_size;
char array[256];
public:
charbox * ptr_next ;
public :
charbox () : ptr_next(NULL)
{
for (int index =0 ; index < array_size ; ++index )
{
array[index]=0;
}
}
char& operator[] (int index)
{
if( (index > array_size) || (index == array_size) )
{
throw int(index);
}
return array[index];
}
void * operator new(size_t x)
{
try
{
return ( ::operator new(x) ) ;
}
catch (std::bad_alloc & badexcption)
{
throw badexcption;
}
}
};
const charbox:: array_size =256;
class TestVector
{
int use; //how many arrays is used?
int count; //the space is enough?
int lengh; //how many arrays will be created?
charbox * const ptr_vector; //point to the first charbox !
charbox * ptr_last; //point to the last current one!
charbox * ptr_charbox; //in order to create or delete !
public:
// TestVector (int conut) : ptr_vector (operator new(sizeof(charbox)*conut )
TestVector () : ptr_vector (new charbox),use(1),ptr_charbox(NULL) ,ptr_last(NULL)
,count(0) ,lengh(0) {}
char& operator [] (int index)
{
if( index <0 )
{
throw int (index);
}
lengh=index /256 ;
count=lengh + 1 - use;
if( count < 0 || count == 0 ) //the space is enough!
{
ptr_charbox=ptr_vector;
for (int x=0 ; x<lengh ; ++x)
{
ptr_charbox=ptr_vector->ptr_next;
}
return ptr_charbox->operator [] (index % 256);
}
if( count > 0 ) //the space is not enough!
{
for ( int size =0 ; size < count ; ++size )
{
ptr_charbox=new charbox ;
ptr_last->ptr_next=ptr_charbox;
ptr_last=ptr_charbox;
++use;
}
return ptr_last->operator [] (index % 256);
}
return ptr_vector->operator [] (0); //error!
}
~TestVector()
{
for(int z =0 ;z < use ; ++z)
{
ptr_charbox=ptr_vector;
ptr_last=ptr_charbox->ptr_next;
delete ptr_charbox;
ptr_charbox=ptr_last;
}
}
};
//*************************************************************************
//if buf is globe is not good idea ,we can make it become static
//but I will create a class above this line with array of can change size!
//int this way , the efficiency may be advance!
//*************************************************************************