java中StringBuffer/StringBuilder的大小

发布于 2024-11-29 21:48:14 字数 135 浏览 1 评论 0原文

All,

为什么建议将 StringBuffer/StringBuilder 对象的大小初始化为 2^{1...n} 的大小(虽然通常会这样是> 64)。这样做会带来什么优势/优化?

All,

Why is it suggested that the size of the StringBuffer/StringBuilder object should be initialized to a size of 2^{1...n}(Though usually it would be > 64). What would be the advantage/optimization would be achieved doing so?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初吻给了烟 2024-12-06 21:48:14

这个建议是因为,默认情况下,构造函数将使用 大小 16 对其进行初始化,并且只要超出此容量,它就会加倍并创建一个新的。

因此,如果您确定将使用超过 16 个空格,则应该使用更高的值对其进行初始化。

The suggestion is because, by default the constructor will initialize it with a size of 16, and whenever this capacity is exceeded it will double and create a new one.

Therefore if you know for sure you will be using more than 16 spaces, you should initialize it with a higher value.

烟酒忠诚 2024-12-06 21:48:14

这样做会带来什么优势/优化?

我认为这样做没有任何好处。

我的建议是选择一个比预期尺寸稍大一点的初始尺寸……如果您有一个不错的估计的话。如果您没有估计,那么提供初始大小根本不会获得太多好处。

使用明显高估的初始大小并不是一个好主意。它浪费空间,并且 JVM 必须将您在某个时刻不使用的所有字符归零,这会消耗 CPU/内存周期。

[应该可以根据经验计算出低估和高估大小的成本,并与使用默认初始大小的成本进行比较。然而,这些数字可能取决于 JIT 优化器的性能,以及内存复制速度与归零速度之类的因素。换句话说,它们将是特定于平台的。]

What would be the advantage/optimization would be achieved doing so?

I don't think there is any advantage at all in doing this.

My advice would be to pick an initial size that is just a bit larger than the expected size ... if you have a moderately good estimate. If you don't have an estimate, you won't gain much by supplying an initial size at all.

Using an initial size that is a significant over-estimate is not a good idea. It wastes space, and the JVM will have to zero all of those characters that you don't use at some point which costs CPU / memory cycles.

[It should be possible empirically figure out the cost of under- and over-estimating the sizes, and compare with the costs of using the default initial size. However, the numbers are likely to depend on how good the JIT optimizer is, and things like how fast memory can be copied versus how fast it can be zeroed. In other words, they will be platform specific.]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文