C# · 12月 23, 2021

c# – 字符串与字节数组,性能



One performance trick to working with any language,C++,Java,C# is
to avoid object creation. It’s not the cost of allocation or GC,its
the cost to access large memory arrays that dont fit in the cpu cache.

Modern cpu’s are much faster than their memory. They stall for many,
many cycles for each cache miss. Most of the cpu transister budget is
allocated to reduce this with large caches and lots of ticks.

GPU’s solve the problem differently by having lots of threads ready to
execute to hide memory access latency and have little or no cache and
spend the transistors on more cores.

So,for example,rather than using String’s and split to parse a
message,use byte arrays that can be updated in place. You really want
to avoid random memory access over large data structures,at least in
the inner loops.



解决方法 他说如果你将一个块文本分割成单独的字符串对象,那么这些字符串对象的位置要比大量的文本更差.每个字符串及其包含的字符数组将会在内存中的其他位置;他们可以遍布整个地方.在处理数据时,内存缓存很可能不得不进入和退出以访问各种字符串.相比之下,一个大阵列具有最佳可能的位置,因为所有的数据都在一个内存区域,高速缓存冲击将被保持在最低限度.