1.for循环数组拷贝方式
import java.util.Date;
public class Vector1 {
public static void main(String[] args) {
Vector1 v = new Vector1();
long time = new Date().getTime();
for (int i = 0; i < 40000; i++) {
v.add("H");
}
System.out.println(new Date().getTime() - time);
System.out.println(v.size());
System.out.println(v.get(0));
}
private Object[] objs;
public void add(Object obj) {
if (objs == null) {
objs = new Object[1];
objs[0] = obj;
} else {
Object[] objs1 = new Object[objs.length + 1];
for (int i = 0; i < objs.length; i++) {// for循环数组拷贝
objs1[i] = objs[i];
}
objs1[objs.length] = obj;
objs = objs1;
}
}
public int size() {
return objs.length;
}
public Object get(int index) {
return objs[index];
}
}
运行结果:
6151
40000
H
2.内存数组拷贝方式
import java.util.Date;
public class Vector2 {
public static void main(String[] args) {
Vector2 v = new Vector2();
long time = new Date().getTime();
for (int i = 0; i < 40000; i++) {
v.add("H");
}
System.out.println(new Date().getTime() - time);
System.out.println(v.size());
System.out.println(v.get(0));
}
private Object[] objs;
public void add(Object obj) {
if (objs == null) {
objs = new Object[1];
objs[0] = obj;
} else {
Object[] objs1 = new Object[objs.length + 1];
System.arraycopy(objs, 0, objs1, 0, objs.length);// 内存数组拷贝比for循环数组拷贝快
objs1[objs.length] = obj;
objs = objs1;
}
}
public int size() {
return objs.length;
}
public Object get(int index) {
return objs[index];
}
}
运行结果:
3544
40000
H
3.最快的数组拷贝方式(每次多申请数组长度50%的数组空间)
import java.util.Date;
public class Vector3 {
public static void main(String[] args) {
Vector3 v = new Vector3();
long time = new Date().getTime();
for (int i = 0; i < 40000; i++) {
v.add("H");
}
System.out.println(new Date().getTime() - time);
System.out.println(v.size());
System.out.println(v.get(0));
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Object[] objs;
private int index = 0;
public void add(Object obj) {
if (objs == null) {
objs = new Object[2];
objs[index] = obj;
index = index + 1;
} else {
if (index == objs.length) {// 不够就申请
int max = (int) ((objs.length * 0.5) + objs.length + 1);
Object[] objs1 = new Object[max];// 申请新的容器
// 搬运老数据到新数组上
System.arraycopy(objs, 0, objs1, 0, objs.length);
objs = objs1;
}
objs[index] = obj;
index = index + 1;
}
}
public int size() {
return index;
}
public Object get(int index) {
return objs[index];
}
}
运行结果:
0
40000
H
体会到了一种编程思想,服务器性能与编程......