这是编写此代码块的更有效方法

时间:2014-12-17 16:36:21

标签: java if-statement for-loop execution

我正在编写一个模块,它将根据某些输入文件生成DDL。我想弄清楚哪种方式更有效率。

这:

for (int i = 0; i < Common.testFields.size(); i++) {
    line = "";
    line += "  " + Common.testFields.get(i).toString() + "  ";
    line += Common.dataTypes.get(i).toString(); 
    if (i != Common.testFields.size() - 1) 
        line += ",";
    ddl += line;
    if (i != Common.testFields.size() - 1) 
        ddl += "\n";
}

或者这个:

for (int i = 0; i < Common.testFields.size(); i++) {
    line = "";
    line += "  " + Common.testFields.get(i).toString() + "  ";
    if (i == Common.testFields.size() - 1) {
        line += Common.dataTypes.get(i).toString(); 
        ddl += line;
    }
    else {
        line += Common.dataTypes.get(i).toString() + ",";
        ddl += line + "\n";
    }
}

我使用for计算了两个System.currentTimeMillis()循环的执行时间,但是当我打印出已用时间时,它会打印出1毫秒。 Common.testFields.size()目前为165.考虑到这两者的复杂性与O(n)相同,如果Common.testFields.size()相当大,比现在大1000或甚至10000倍,其中一个,如果有的话会更快?

3 个答案:

答案 0 :(得分:4)

我的最爱&#34;加入&#34;模式是这样的:

StringBuilder builder = new StringBuilder();
String separator = "";

for (int i = 0; i < Common.testFields.size(); i++) {
    builder.append(separator)
           .append("  ")
           .append(Common.testFields.get(i))
           .append("  ")
           .append(Common.dataTypes.get(i));

    separator = ",\n";
}

String ddl = builder.append("\n").toString();

没有特殊情况&#34;如果是#34;或者&#34;如果是第一个&#34;必要的。

答案 1 :(得分:1)

这个怎么样......

//assuming
String ddl = new String("")

for (int i = 0; i < Common.testFields.size(); i++){
    ddl += "  "
         + Common.testFields.get(i).toString()
         + "  "
         + Common.dataTypes.get(i).toString()
         + ",\n";
}

ddl = ddl.substring(0, ddl.length()-3);
ddl += "/n";

答案 2 :(得分:0)

如果你想确定,你必须进行衡量。

// the JIT might be able to do this optimisation, but lets be sure
StringBuilder builder = new StringBuilder();

// resolve this just once (assuming it stays the same during your loop), you never know how the VM is going to do this lookup
// also change type of list to the type of Common.testFields
ArrayList<? extends Object> fields = Common.testFields;
ArrayList<? extends Object> data = Common.dataTypes;
for (int i = 0, size = fields.size(); i < size; i++) {
    builder.append("  ").append(fields.get(i)).append("  ").append(data.get(i));
    if (i != size - 1)
        builder.append(",\n");
}
ddl = builder.toString(); // or += or whatever the previous state of ddl is...