1. 程式人生 > >幾種陣列拷貝的效能

幾種陣列拷貝的效能

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

                    體會到了一種程式設計思想,伺服器效能與程式設計......