哪个是实现迭代语句最有效的内存方式?

时间:2013-02-21 16:48:35

标签: java performance algorithm

我知道有办法知道循环成本或迭代声明,但我想知道两件事:

第一 这两个上市中哪一个更具成本效益? (或者如果有更好的方法,我会全力以赴):

更新:然后问题是:其中2个中的哪个会正确使用内存/ GC? 请注意,reqObjresObj的“值”对于下一个循环不是必需的。

for (TransactionLog transactionLog : transactionLogList) {
 RequestObj reqObj = new RequestObj();
 ResponseObj resObj;
 try {

  //do things with these 2 babes and the transactionLog

 } catch (WhateverException ex) {
  log.error("Error in XYZ while doing whatever", ex);
  //execute code without throwing anything up
 } finally {
  reqObj = null;
  resObj = null;
 }
}

RequestObj reqObj = new RequestObj();
ResponseObj resObj;
for (TransactionLog transactionLog : transactionLogList) {
 try {
  //do things with these 2 babes and the transactionLog

 } catch (WhateverException ex) {
  log.error("Error in XYZ while doing whatever", ex);
  //execute code without throwing anything up
 } finally {
  //do something
 }
}

和第二。 在哪里可以找到一个好的地方/书籍/网站来学习这个“算法最佳实践”和函数O(字母)来计算交互的陈述成本?

PD:抱歉我的英语......他看起来不太好看。的xD

2 个答案:

答案 0 :(得分:0)

本地对象更清晰,更不容易出错,垃圾收集器可以很好地处理这些对象。对于像StringBuilder这样的可重用对象,你可以在每个周期清除而不是做新的StringBuilder我也很惊讶它(也就是某人)。

正如设置为null是初学者的签名。

答案 1 :(得分:-1)

如果RequestObjResponseObjAutoCloseable(或者您是这样实施的),那么您应该考虑使用 try-with-resources 块使用Java 7.它会处理他们需要或者你想要的任何清理,没有额外的finally(或者finally中的额外捕获);这些异常被抑制了。

try( RequestObj reqObj = new RequestObj(); ResponseObj resObj = ... ) {
  // Do stuff

} catch (WhateverException ex) {
  log.error("Error in XYZ while doing whatever", ex);
  // execute code without throwing anything up
} 

// No finally block required

您不应该担心GC /内存问题,因为在您的情况下,这似乎是过早优化。保持代码清洁和可读性更好。

有关详细信息:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

相关问题