在struct []中分配char *指针值(谁是结构成员)的最优化方法

时间:2015-10-20 20:09:35

标签: c++ arrays performance char

我正在尝试制作一些结构集合,其中一些成员是一种字符串,而且字符串是昂贵的'处理我试图通过使用指针来最大化性能。

我尽力从教程中学习,但c ++中有很多不同类型的字符串。

如果值的类型为strVal,设置char*的最快方式是什么?

DataCollection.h

extern "C" __declspec(dllexport) void GetContCollection(int CollectionLength,int StrLength, DataContainer** Collection);

typedef struct {
int iValue;
char* strValue;
}DataContainer;

DataCollection.cpp

extern "C" __declspec(dllexport) void GetContCollection(int CollectionLength,int StrLength, DataContainer** Collection)
{
    *Collection = (DataContainer*)LocalAlloc(0, CollectionLength * sizeof(DataContainer));  
    // say i need to get a record from database returning a char array
    // and i use current datatype
    *DataContainer CurElement = *Collection;

   // iteration on each element of the collection
   for(int i=0, i< CollectionLength; i++, CurElement++)
   {
       char* x = getsomeValuefromSystemasChar();

       //.... how to assign CurElement->strValue=?
       CurElement->strValue =// kind of Allocation is needed or ....just assign
       //next, do i have to copy value or just assign it ? 
       CurElement->strValue = x or strcpy(dest,source)// if copying must take place which function would be the best?
   }
}

设置CurElement的正确和最优化方式是什么?

1 个答案:

答案 0 :(得分:2)

对这个问题的评论和编辑使得这个答案的大部分已经过时了。我保留它纯粹是为了任何可能浏览编辑历史的人。保持有效的部分在本答复的最后。

如果,正如问题所说,结构中所有char *将引用的是字符串文字,那么你不需要分配内存,或者采取特殊步骤的方式分配时。

字符串文字具有静态存储持续时间,因此您只需将其地址分配给指针,一切都会正常。你不想让任何人不小心写入字符串文字,所以你通常想要使用指向const的指针:

typedef struct {
    int iValue;
    char const * strValue;
} DataContainer;

然后当你需要分配时,只需指定:

extern "C" __declspec(dllexport) void GetContCollection(int CollectionLength,int StrLength, DataContainer** Collection)
{
    // ...
   CurElement->strValue = "This is a string literal";
}

您可以(绝对)对具有静态存储持续时间的字符串文字进行计数,因此毫无疑问这将起作用。由于你只是指定一个指针,它也会很快。

不幸的是,它也有些脆弱 - 如果有人在这里分配字符串文字以外的东西,它可以很容易地破解。

这将我们带到下一个问题:你是否真的在处理字符串文字 。虽然您特别询问字符串文字,但您显示的演示代码看起来并不像是处理字符串文字 - 如果不是这样,那么上面的代码就会破坏。

如果必须处理,

我要说只使用std::string。如果你坚持自己做这件事,那么你很有可能会产生破碎的东西,并且很少(几乎没有)你有机会在不破坏任何东西的情况下获得巨大的速度优势。

相关问题