1. 程式人生 > 其它 >StringBuffer和StringBuilder單執行緒誰的效能更好

StringBuffer和StringBuilder單執行緒誰的效能更好

技術標籤:JVMjava

結論:不一樣的量級,結果不一樣。原因還在分析中,有直到的大拿幫忙回覆一下

package com.example.jvm;

import org.junit.Test;

/**
 * @Author jvm
 * @Date 2021/1/28 07:50
 * StringBuffer和StringBuilder效能測試
 * count:1W
 *  StringBufferExecutor: 7
 *  StringBuilderExecutor: 1
 * count:1KW
 *  StringBufferExecutor: 347
 *  StringBuilderExecutor: 357
 */
public class StringTest { int count = 10000000; @Test public void test() { executeCount(new StringBufferExecutor()); executeCount(new StringBuilderExecutor()); } void executeCount(Executor executor) { long cu = System.currentTimeMillis(); for (int i = 0;
i < count; i++) { executor.execute(); } System.out.printf("%s: %d\n", executor.getClass().getSimpleName(), System.currentTimeMillis() - cu); } public interface Executor { void execute(); } public static class StringBufferExecutor implements
Executor { @Override public void execute() { StringBuffer sb = new StringBuffer(); sb.append("1"); sb.append("2"); } } public static class StringBuilderExecutor implements Executor { @Override public void execute() { StringBuilder sb = new StringBuilder(); sb.append("1"); sb.append("2"); } } }