在java中搜索数组时经过的时间问题

时间:2014-05-29 01:56:54

标签: java arrays performance

所以我必须在java中编写一个程序,它必须在数组中向前和向后搜索一个对象(String)并查看哪一个更快。当我进行测试时,程序需要花费更长的时间才能在数组的开头找到一个对象然后向后移动。我很困惑因为它应该更快,因为它在数组的开头。有人可以向我解释我做错了什么吗?

import java.util.Scanner;
import java.util.Arrays;

public class LinearStringSearch{

    public static long startTime;
    public static long endTime;
    public static long startTimeB;
    public static long endTimeB;


    public static void printArray(String arr[]){
        for(int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
    }


    public static void main(String[] args){

        Scanner input = new Scanner(System.in);
        System.out.println("Please enter a word and we will check our database for it");
        String a = input.nextLine();
        String [] words = new String[10];
        for (int i = 0; i < words.length; i++){
            words[i] = "Test " + (i + 1);
        }


        long startTime = System.nanoTime();
        for(int i = 0; i < words.length; i++){
            if (a.equals(words[i])){
            System.out.println("It is located at index: " + i);    
            break;
            }
        }
        long elaspedTime = System.nanoTime() - startTime;

        System.out.println("Going from the front, it took " + elaspedTime);

        long startTimeBack = System.nanoTime();
        for (int i = words.length-1; i >= 0; i--){
            if (a.equals(words[i])){
            System.out.println("It is located at index: " + i);    
            break;
            }


        }
        long elapsedTimeB = System.nanoTime() - startTimeBack;

        System.out.println("Going from the back, it took " + elapsedTimeB);

    }

}

2 个答案:

答案 0 :(得分:1)

如果数组大小为10,则执行速度可能太快,无法看到有意义的结果。如果您将数组大小更改为1,000,000(如下所示)并搜索&#34;测试1&#34;,您将看到明显的结果:

String [] words = new String[1000000];

这是输出:

Please enter a word and we will check our database for it
Test 1
It is located at index: 0
Going from the front, it took 198038
It is located at index: 0
Going from the back, it took 17801149

答案 1 :(得分:0)

通常,使用这样的基准测试无法知道代码在实际程序中的执行情况。 JVM可以使用字节码解释器开始执行程序,然后,如果在方法中花费了大量时间,则决定JIT它并跳转到优化的机器代码(即堆栈替换,请参阅the hotspot glossarry)。

有关详细信息,请参阅文章how do i write correct micro benchmark in java 上的讨论和答案。

对于java,有一些基准测试框架可以帮助您进行适当的基准测试的某些方面,例如:多次运行和结果平均。请查看JUnitBenchmarksCaliper