【问题标题】:Recursive Call Performance递归调用性能
【发布时间】:2018-10-31 19:16:06
【问题描述】:

Job 定义如下:

class Job<T> {
  String Class<T> type;

  T execute() throws Exception {
    return type.newInstance();
  }

  static <T> T execute(Job<T> aJob, Job<T>... jobs) {
    //... some lines of unrelated code...
    try{        
      return aJob.execute();
    } catch(Exception e){
      if(jobs.length == 0) throw new RuntimeException(e);
      return execute(jobs[0], Arrays.copyOfRange(jobs, 1, jobs.length));
    }
  }
}

需要递归来重用 try-catch 块。如果一份工作 失败了,我打电话给下一份工作。当没有一个作业成功时,我抛出一个包装实际异常的 RuntimeException。这只是一种后备机制。代码和我的不一样,但是结构一样。

让我烦恼的是执行递归调用:

execute(jobs[0], Arrays.copyOfRange(jobs, 1, jobs.length));

我也可以使用队列而不是数组:

T execute(Job<T> aJob, Queue<Job<T>> jobQueue) {  
//...
execute(jobQueue.poll(), jobQueue);
//...

我认为使用数组会产生更好的性能。但是使用队列使代码更具可读性和直观性。不过,我还没有测试过任何一个选项的性能。

  1. 什么样的数据结构会提供更好的性能?
  2. 有没有更好的方法来进行这种递归调用?
  3. 使用 for 循环代替递归会更好吗?

谢谢

【问题讨论】:

  • 您的 reduce 只是一个 for 循环,计算每个 job 的值,然后对它们做一些事情(例如求和或乘积...)对吗?需要实际的预期代码。
  • 这些值是如何聚合的?我只是看到你不断地执行Job并返回任何不聚合的非空值
  • 我编辑了代码,我承认“减少”只是一个糟糕的词选择。 @MạnhQuyếtNguyễn
  • 看我的回答。希望你能明白

标签: java performance recursion data-structures


【解决方案1】:

在这种情况下,我认为您不想一遍又一遍地重复复制,因为您只对一个数组进行操作。

static <T> T execute(Job<T> aJob, int begin, Jobs[] jobs) {
    //... some lines of unrelated code...
    try{        
      return aJob.execute();
    } catch(Exception e){

      // if(jobs.length == 0) throw new RuntimeException(e);
      // The condition changed to begin < jobs.length

      if (begin == jobs.length) throws ... // End of array already

      return execute(jobs[0], begin + 1, jobs); // Advance to the next index. No need to copy the array
    }
}

我们只对单个数组进行操作,不需要复制。

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2015-03-10
    • 2011-10-04
    • 2013-05-19
    相关资源
    最近更新 更多