Skip to content

Instantly share code, notes, and snippets.

@thieux
Last active September 15, 2016 08:19
Show Gist options
  • Save thieux/97a2cb8f94f97fb8307fd936724ea411 to your computer and use it in GitHub Desktop.
Save thieux/97a2cb8f94f97fb8307fd936724ea411 to your computer and use it in GitHub Desktop.

Common misconception about String concatenation in a loop

No worries about contatenating String in a loop if the buffer does not grow.

import org.junit.Test;

// java 8
public class StringConcatLoopTest {

	@Test
	public void very_long_when_concat_increasing_size_string() {
		String buffer = "";
		long start = System.currentTimeMillis();
		for (int i = 0; i < 1000 * 50; i++) {
			buffer += i + "\n";
		}
		long stop = System.currentTimeMillis();

		System.out.println(stop - start); // 6921
		System.out.println(buffer.length()); // 288890
	}

	@Test
	public void quick_when_appending_increasing_size_string() {
		StringBuffer buffer = new StringBuffer();
		long start = System.currentTimeMillis();
		for (int i = 0; i < 1000 * 50; i++) {
			buffer.append(i + "\n");
		}
		long stop = System.currentTimeMillis();

		System.out.println(stop - start); // 68
		System.out.println(buffer.length()); // 288890
	}

	@Test
	public void quick_when_concat_constant_size_string() {
		String buffer = "";
		long start = System.currentTimeMillis();
		for (int i = 0; i < 1000 * 50; i++) {
			buffer = "x" + i + "\n";
		}
		long stop = System.currentTimeMillis();

		System.out.println(stop - start); // 45
		System.out.println(buffer.length()); // 7
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment