如何定义通道的最佳缓冲区大小?

huangapple go评论88阅读模式
英文:

How to define the optimal size of the buffer for a channel?

问题

我知道缓冲区的大小在应用程序性能中起着重要作用,但是如何定义缓冲区大小才是最佳方式呢?在确定大小时应该考虑哪些因素?

类似于"最佳实践"的东西。

英文:

I know that the size of the buffer can play an important role in an application performance, however what is the best way to define a buffer size? What should I think about when sizing?

Something like “best practices”

答案1

得分: 1

为了证明缓冲区大小实际上是性能的一个重要因素,您必须测量性能并尝试不同的大小进行比较。在那时,您已经有了一种找到一个好值的方法(简单地进行测试和比较)。

至于在确定通道大小时需要考虑的因素,那可能是一个不同的问题。首先要考虑的是程序的正确性:也就是说,程序是否按预期运行且没有故障。正如在评论中提到的,在绝大多数情况下,“正确”的值分别是0和1,分别用于同步和非同步通信。

如果您的通道确实需要一个大于1的缓冲区大小,那么您必须确定通道必须同时保存的值的上限或“最坏情况”数量,以避免死锁。如果您无法确定该数字的确切值,那就是没有上限的一个好迹象。例如,如果您有一个递归例程发送消息,可能没有上限。如果是这种情况,您必须重新设计程序以动态方式存储值,例如使用切片。

英文:

To demonstrate that buffer size is actually an important factor in performance, you must measure the performance and try different sizes to compare. At that point, you already have a method to find a good value (simply keep testing and comparing).

As far as what to think about when sizing a channel, that may be a different question. The first thing to consider is the correctness of the program: meaning, will the program operate as intended and without faults. As mentioned in the comments, in a vast majority of cases the "correct" value is either 0 or 1, in synchronized and un-synchronized communication respectively.

If your channel does require a buffer size of more than 1, then you must determine the upper bound, or "worst case" number of values that the channel must hold at once to avoid deadlocks. If you can't determine what that number is exactly, that's a good sign that there is no upper bound. For example, if you have a recursive routine that sends messages, there may be no upper bound. If that is the case, you must redesign your program to store the values in a dynamic, way such as a slice.

huangapple
  • 本文由 发表于 2021年9月24日 12:17:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/69309500.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定