See this code:
private final Node head = new Node("");
private Node tail = head;
private Appendable append0(CharSequence csq) {
charCount += csq.length();
Node newNode = new Node(csq);
tail.next = newNode;// 1!
tail = newNode;// 2!
return this;
}
In performance test, this code cost: 3055
ms
If I comment 1
and 2
:
Node newNode = new Node(csq);
//tail.next = newNode;// 1!
//tail = newNode;// 2!
It cost: 8
ms
If I comment 1
:
Node newNode = new Node(csq);
//tail.next = newNode;// 1!
tail = newNode;// 2!
It cost: 138
ms
If I comment 2
:
Node newNode = new Node(csq);
tail.next = newNode;// 1!
//tail = newNode;// 2!
It cost: 143
ms
If I swap 1
and 2
:
Node newNode = new Node(csq);
tail = newNode;// 2!
tail.next = newNode;// 1!
It cost: 136
ms
3055 vs 140 ?????
Why the performances so big different????
Here is the full code:
public class CharsAppender implements Appendable {
private int charCount = 0;
private final Node head = new Node("");
private Node tail = head;
@Override
public Appendable append(CharSequence csq) {
return append0(csq);
}
@Override
public Appendable append(CharSequence csq, int start, int end) {
CharSequence chars = csq == null ? BDefault.nullString() : csq;
return append0(BString.subRef(chars, start, end));
}
@Override
public Appendable append(char c) {
return append0(Character.toString(c));
}
private Appendable append0(CharSequence csq) {
charCount += csq.length();
Node newNode = new Node(csq);
tail.next = newNode;
tail = newNode;
return this;
}
private static class Node {
private final CharSequence value;
private Node next;
private Node(CharSequence value) {
this.value = value;
}
public CharSequence getValue() {
return value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public static void main(String[] args) {
int times = 10000000;
String message = "fasasgadfgdfgfd923fr";
StringBuilder sb = new StringBuilder();
long s1 = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
sb.append(message);
}
System.out.println("StringBuilder cost: " + (System.currentTimeMillis() - s1));
CharsAppender ca = new CharsAppender();
long s2 = System.currentTimeMillis();
for (int i = 0; i < times; i++) {
ca.append(message);
}
System.out.println("CharsAppender cost: " + (System.currentTimeMillis() - s2));
}
}