[英]Accessing in a statically-allocated array VS accessing via a pointer to a statically-allocated array
我需要在一个数组中存储多个字符串(它们将保持不变并且不会被修改),并多次访问它们,我们希望实现尽可能快的查找。 以下哪项将提供更快的访问权限:
方法1:
const char* string_literal[] = {"Test1","Dummy","Dummy","Test2","Test3","Dummy"}; // storing as string literals
... ... ... ...
... ... ... ...
const char* string_literal1000[]= {"Beta1","Beta2","Beta3"};
方法二:
const char test1ptr[] = "Test1",
const char test2ptr[] = "Test2",
const char test3ptr[] = "Test3",
const char dummyptr[] = "Dummy",
const char* string_ptr1 [] = {test1ptr,dummyptr,dummyptr,test2ptr,test3ptr,dummyptr}; // storing as pointers
... ... ...
const char* string_ptr1000[] = {"Beta1","Beta2","Beta3"};
要么; 方法1和方法2会产生相同的效果吗?
注意:
string_literal1000无法编译。
简单的答案:说出相同的性能(因为分配模式相同)。
但是,您甚至没有显示使用模式时,也希望我们比较速度,这很有趣。
现在,我可以想象一下您可以使用以下模式进行一些优化的情况:IFF您知道最大条目的长度(它们看起来很小),可以通过将整个表打包为单个char []来优化整个表。 ],其中包含对齐并填充的单个字符串,且字节数不错(例如,OP中显示的字符串为16或32)。
如果没有有关实际代码方案的更多信息,推荐这种方法(IMO)将是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.