Java 需要优化以下代码的建议吗
我需要一些指导,如何优化下面的代码。可以看到,我每次都创建一个新对象来设置每个值。我怎样才能做得更好Java 需要优化以下代码的建议吗,java,Java,我需要一些指导,如何优化下面的代码。可以看到,我每次都创建一个新对象来设置每个值。我怎样才能做得更好 Balance[] balance = new Balance[3]; CurAmt curAmt = new CurAmt(); Balance bal = new Balance(); bal.setBalType("currentBalance"); curAmt.setCurCode(entry.getValue().get(0).getAs("CURRENT_BALANCE_CURRE
Balance[] balance = new Balance[3];
CurAmt curAmt = new CurAmt();
Balance bal = new Balance();
bal.setBalType("currentBalance");
curAmt.setCurCode(entry.getValue().get(0).getAs("CURRENT_BALANCE_CURRENCY_CODE"));
curAmt.setContent(entry.getValue().get(0).getAs("CURRENT_BALANCE"));
bal.setCurAmt(curAmt);
balance[0] = bal;
CurAmt curAmt1 = new CurAmt();
Balance bal1 = new Balance();
bal1.setBalType("availableBalance");
curAmt1.setCurCode(entry.getValue().get(0).getAs("AVAILABLE_BALANCE_CURRENCY_CODE"));
curAmt1.setContent(entry.getValue().get(0).getAs("AVAILABLE_BALANCE"));
bal1.setCurAmt(curAmt1);
balance[1] = bal1;
CurAmt curAmt2 = new CurAmt();
Balance bal2 = new Balance();
bal2.setBalType("interestEarnedYtd");
curAmt2.setCurCode(entry.getValue().get(0).getAs("YTD_CURRENCY_CODE"));
curAmt2.setContent(entry.getValue().get(0).getAs("TD_AMOUNT"));
bal2.setCurAmt(curAmt2);
balance[2] = bal2;
Obj.setBalance(balance);
如果您谈论的是代码性能,我只能看到一个优化。您对此进行了6次评估,JIT编译器可能无法对其进行优化:
entry.getValue().get(0)
执行一次并将该值赋给临时变量。(目前还不清楚这是否会产生显著的差异。您这样做只是出于性能原因,建议您首先对应用程序进行分析。优化不是性能热点的应用程序代码毫无意义。)
如果您谈论的是程序员的效率(即代码可读性),我可以看到一个代码块使用不同的参数重复了3次。你可以把它变成一种方法;e、 g
private Balance createBalance(Value v, String type, String currency, String balance) {
CurAmt curAmt = new CurAmt();
Balance bal = new Balance();
bal.setBalType(type);
curAmt.setCurCode(value.getAs(currency));
curAmt.setContent(value.getAs(ballance));
bal.setCurAmt(curAmt);
return bal;
}
然后用适当的参数调用它。为什么要更改它?第一件事可能是构造函数参数,而不是setter调用。谢谢@Stephen。。你能澄清一下这里的
Value
type类是什么吗?它表示entry.getValue().get(int)
返回的任何东西的类型。根据需要进行更改。感谢@Stephen的帮助