多个数组合并为一个数组的方法与性能
来源:互联网 发布:编发软件 编辑:程序博客网 时间:2024/06/07 08:57
工作是遇到合并数组的问题,想到了两个方法。同事说利用System.arraycopy()方法晦涩难懂,没有用List转换来的清晰易懂。所以我就编写了两个方法区测试其性能。代码如下:
package com.lys.test;import java.util.ArrayList;import java.util.List;public class TestCombineArrays { public static void main(String[] args) { String[] str1 = {"a","b","c"}; String[] str2 = {"a","b","c"}; String[] str3 = {"a","b","c"}; long start = System.currentTimeMillis(); for(int i=0;i<100000;i++){ String[] result1 = combineArrays1(str1,str2,str3); } long end = System.currentTimeMillis(); System.out.println("combineArrays1: cost time=="+(end-start)); long start1 = System.currentTimeMillis(); for(int i=0;i<100000;i++){ String[] result1 = combineArrays2(str1,str2,str3); } long end1 = System.currentTimeMillis(); System.out.println("combineArrays2: cost time=="+(end1-start1)); } /** * 利用List作中介合并 * @param info * @return */ public static String[] combineArrays1(String[]... info){ List<String> list = new ArrayList<String>(); for(String[] arr:info){ for(String s:arr){ list.add(s); } } String[] result = new String[list.size()]; for(int i=0;i<list.size();i++){ result[i] = list.get(i); } return result; } /** * 利用System.arraycopy()方法 * @param info * @return */ public static String[] combineArrays2(String[]... info){ int length = 0; for(String[] arr:info){ length += arr.length; } String[] result = new String[length]; int index = 0; for(String[] str:info){ System.arraycopy(str, 0, result, index, str.length); index += str.length; } return result; }}
总的来说,利用List要比System.arraycopy方式更加耗费性能,所耗时间是其4倍之多。活到老学到老~
1 0
- 多个数组合并为一个数组的方法与性能
- php中多个数组合并为一个数组
- 如何优雅的将多个数组合并成一个数组(去重)
- java 多个数组合并成一个数组,一个数组分割成多个数组!
- PHP 对多个数组合并去重&以及数组键值的翻转
- 多个数组转化为一个数组的方法
- PHP多个数组合并(递归的进行)
- 使用简单的JS代码让多个数组合并
- 求数组中和为某个值的一个组合
- 从大小为n的数组中取出m个数的组合
- 微软:找出数组中和为N+1的的组合个数
- 求数组中和为给定数的所有组合的个数
- 15.计算数组中3个数和为0的不重复的组合
- 获取数组的n个数的组合
- 和为指定数的组合个数
- 求数组中任意个数的组合
- 向一个数组中输入5数,并计正数的个数,并求他们之和
- 定义 多个条件判断 组合 为一个判断条件 的方法
- springMVC maven的pom.xml配置文件参考
- Porting:uboot简介、移植、代码阅读、uboot添加启动logo
- 2.23
- HDU5248:序列变换(二分)
- 发票统计(C程序设计进阶 第2周)
- 多个数组合并为一个数组的方法与性能
- 9
- Win XP iso映像文件(附序列号)
- 面向切面编程(AOP)的理解
- web前端一道很“坑”的js面试题
- 头文件
- 算法竞赛入门经典ch1_ex_鸡兔同笼
- c语言中:结构体的内存分配
- HTML5基本元素的使用