Is string concatenaion really that slow?

女生的网名这么多〃 提交于 2019-11-28 07:31:41

Am I doing something wrong in measuring this, or is this supposed to happen?

It's supposed to happen. Constructing a long string using repeated string concatenation is a known performance anti-pattern: every concatenation has to create a new string with a copy of the original string and also a copy of the additional string. You end up with O(N2) performance. When you use StringBuilder, most of the time you're just copying the additional string into a buffer. Occasionally the buffer will need to run out space and need to be expanded (by copying the existing data into a new buffer) but that doesn't happen often (due to the buffer expansion strategy).

See my article on string concatenation for details - it's a very old article, so predates StringBuilder, but the fundamentals haven't changed. (Basically StringBuilder is like StringBuffer, but without synchronization.)

This is exactly what should happen. betterRead takes linear time; inefficientRead takes quadratic time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!