Which is faster, one-dimensional array or two-dimensional array in JAVA?

Go directly to the code and conclusion:

package com.chz.apps.data.test;

import org.junit.Test;

public class DemoTest {

    @Test
    public void stringArrayTest(){
        //准备数据
        String[] bmp1 = new String[4800];
        for (int i = 0 ; i < 4800 ; i++) {
            bmp1[i] = i+"";
        }


        String[][] bmp2 = new String[80][60];
        for (int i = 0 ; i < 80 ; i++) {
            for (int j = 0 ; j < 60 ; j++) {
                bmp2[i][j] = i+"-"+j;
            }
        }

        //第一个测试
        Long start = System.nanoTime();
        for (int y = 0;y<60;y++){
            String res = bmp1[40 + 80*y];
        }
        System.out.println("字符串数组-本次耗时1:"+(System.nanoTime() - start));

        //第二个测试
        start = System.nanoTime();

        for(int y = 0;y<60;y++){
            String res = bmp2[40][y];
        }

        System.out.println("字符串数组-本次耗时2:"+(System.nanoTime() - start));
    }


    @Test
    public void intArrayTest(){
        //准备数据
        int[] bmp1 = new int[4800];
        for (int i = 0 ; i < 4800 ; i++) {
            bmp1[i] = i;
        }


        int[][] bmp2 = new int[80][60];
        for (int i = 0 ; i < 80 ; i++) {
            for (int j = 0 ; j < 60 ; j++) {
                bmp2[i][j] = i+j;
            }
        }

        //第一个测试
        Long start = System.nanoTime();
        for (int y = 0;y<60;y++){
            int res = bmp1[40 + 80*y];
        }
        System.out.println("原始数据类型-本次耗时1:"+(System.nanoTime() - start));

        //第二个测试
        start = System.nanoTime();

        for(int y = 0;y<60;y++){
            int res = bmp2[40][y];
        }

        System.out.println("原始数据类型-本次耗时2:"+(System.nanoTime() - start));
    }

}

Test results for use case 1:

String array - this time 1: 18972
String array - this time 2: 5909

 

Test results for use case 2:

Primitive data type - this time 1: 34523
Primitive data type - this time 2: 3110

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325302076&siteId=291194637