gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:54:14 35 4
gpt4 key购买 nike

(这篇文章是关于高频编程的)

我最近在一个论坛上看到(我认为他们在讨论 Java),如果您必须解析大量字符串数据,最好使用字节数组而不是带有 split() 的字符串。确切的帖子是:

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.

他只是在说“不要使用字符串,因为它们是一个对象,创建对象的成本很高”?或者他在说别的什么?

使用字节数组是否可以确保数据尽可能长时间地保留在缓存中?当您使用字符串时,它是否太大而无法保存在 CPU 缓存中?一般来说,使用原始数据类型是编写更快代码的最佳方法吗?

最佳答案

他的意思是,如果您将大块文本分解为单独的字符串对象,那么这些字符串对象的局部性 要比大文本数组差。每个字符串及其包含的字符数组都将位于内存中的其他位置;它们可以遍布各处。当您处理数据时,内存缓存很可能必须反复进出以访问各种字符串。相比之下,一个大数组具有最佳的局部性,因为所有数据都在内存的一个区域上,并且缓存抖动将保持在最低限度。

当然,这也有限制:如果文本非常非常大,而您只需要解析其中的一部分,那么与大块文本相比,这几个小字符串可能更适合缓存。

关于c# - 字符串与字节数组,性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7876594/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com