首页 > 其他 > 详细

几种数组拷贝的性能

时间:2014-03-14 12:10:52      阅读:443      评论:0      收藏:0      [点我收藏+]

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

                    体会到了一种编程思想,服务器性能与编程......

 

 


 

几种数组拷贝的性能,布布扣,bubuko.com

几种数组拷贝的性能

原文:http://blog.csdn.net/a1638221216/article/details/21196915

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!