1

I have a piece of code that needs to be run on a separate thread to improve performance. An example of where all the methods to be used by the Runnable are outside the Runnable class:

public class MyClass{
    public void myMethod() {
        new Runnable(){
            @Override
            public void run() {
               task1();
               task2();
               task3();
            }
        }
    }

    public void task1(){

    }

    public void task2(){

    }

    public void task3(){

    }
}

An example of where all the methods to be used by the Runnable are inside the Runnable class:

public class MyClass{
    public void myMethod() {
        new Runnable(){
            @Override
            public void run() {
               task1();
               task2();
               task3();
            }

            public void task1(){

            }

            public void task2(){

            }

            public void task3(){

            }
        }
    }
}

I'm in a situation where any tiny bit of improvement in performance will make a significant improvement.

Assafs
  • 3,257
  • 4
  • 26
  • 39
Mutai Mwiti
  • 487
  • 1
  • 7
  • 20
  • No, java will copy the code of the `tasks` in the part of code where you call them – Luca Nicoletti Sep 21 '17 at 09:15
  • 3
    Don't guess, use benchmarks. Look at Java JMH. – kan Sep 21 '17 at 09:20
  • @LucaNicoletti Rubbish. Java doesn't copy code anywhere, let alone as you assert. – user207421 Sep 21 '17 at 09:27
  • 3
    @MutaiMwiti You are seriously unlkely to get any benefit from micro-optimizations like this. You need to concern yourself with what happens *inside* these methods. – user207421 Sep 21 '17 at 09:28
  • Theoretically, there should not be much difference. But, just try it practically and benchmark it. – Amber Beriwal Sep 21 '17 at 09:37
  • @EJP look [here](https://stackoverflow.com/a/3925068/6439023). Java compiler CAN replace function calls. – Luca Nicoletti Sep 21 '17 at 09:42
  • 1
    @LucaNicoletti You're doubly wrong. The Java compiler doesn't do anything. The JIT *can* **inline** methods, but that's not what you were describing. – Kayaman Sep 21 '17 at 09:43
  • [JIT](https://en.wikipedia.org/wiki/Just-in-time_compilation) Just In Time Compilation. Who does this? Maybe the compiler? – Luca Nicoletti Sep 21 '17 at 09:46
  • 1
    @LucaNicoletti The Java compiler is `javac`. The `JIT` is a different compiler. There's a significant difference between them. – Kayaman Sep 21 '17 at 09:51
  • @LucaNicoletti 'Java compiler *can* replace function calls' is not the same thing as 'Java *will* copy the code'. If you're talking about inlining by the HotSpot JVM, it would help if you used the same terminology as everybody else. – user207421 Sep 21 '17 at 10:04
  • @EJP my bad, wrong terminology. But that was what I meant, btw, we're OT. – Luca Nicoletti Sep 21 '17 at 10:23

0 Answers0