垂直打印字符串!哪个是时间和复杂性的最佳方法?

时间:2014-03-28 11:39:29

标签: java string

我正在编写3种方法,可以垂直打印输入字符串(一行)。但我不知道最好的方法,因为使用System.nanoTime()进行基准测试时会发生很大变化,我的意思是如果我计算过程开始和结束之间的时间差。 请根据您的知识建议哪个是最好的或更好的。

代码段#1

/**
 * Prints all the characters in the argument string vertically using loop
 * @param str
 */
public static void toVertStringLoop(String str){

    if(str != null && !"".equals(str)){
        int strLen = str.length();

        for (int i=0; i<strLen; i++){
            System.out.println(str.charAt(i));
        }

    }

}

代码段#2

/**
 * Prints all the characters in the argument string vertically using recursion
 * @param str
 */
public static void toVertStringRecur(String str){

    if (str != null && !"".equals(str)){

        System.out.println(str.charAt(0)); //print the first character
        toVertStringRecur(str.substring(1, str.length())); //recursively call removing the first character
    }
}

代码段#3

/**
 * Prints all the characters in the argument string vertically using for-each loop
 * @param str
 */
public static void toVerticalStringIterator(String str){

    //for-each loop needs array or Iterator instance
    for(char ch : str.toCharArray()){
        System.out.println(ch);
    }

}

2 个答案:

答案 0 :(得分:0)

请不要使用Java制作C ++。

最好的方法是编写最易理解的代码。基于此,我更倾向于使用方法3

所有这些方法都有一个缺点 - 所有这些方法都使用System.out::println,这对运行应用程序的时间影响最大​​。如果你真的必须以这种方式处理大量数据,那么你应该考虑并行化算法或者只使用Java 8提供的parallelStream

正如邓肯(在你的帖子中的评论中所说) - 另一个主题是Java中的基准测试。您应该阅读微基准测试 - 这是一个非常复杂的问题,主要是因为JIT和内部JVM优化。

答案 1 :(得分:0)

Code snippet #3是更好的一个。因为Code snippet #2包括递归方法调用,其中JVM必须维护堆栈(这会降低性能并增加额外的JVM)以及Code snippet #1中的位置Code snippet #3的效果相同但由于for-each循环导致性能略有不同(阅读: Is there a performance difference between a for loop and a for-each loop?

相关问题