Max
Max

Reputation: 6239

Better to use object method during initialization or after, if you only have one method?

This question is bound to scream poor programming practice, however, I'm curious if there is any performance risk involved here.

Imagine you have a class that only has one method attached (excluding the constructor) to it, for simplicity sake we'll say:

public class TestClass{

public TestClass(){

    // Set values or whatever you want in the constructor

}
public String printString(){

    System.out.println("print");
}
}

Now considering there is only one method, obviously anytime you use the class you'll probably want to call the method printString. So are there any negatives (besides sanity) to putting a call to printString in the constructor? Rather than doing testClass test = new testClass() then making a call test.printString()?

Again, this question is about performance - not programming practice.

Upvotes: 1

Views: 61

Answers (3)

Yogendra Singh
Yogendra Singh

Reputation: 34367

There is no performance difference in opinion as compiler has same statements to compile (whether you put the statement in calling class or in constructor) and JVM has exact statements to execute.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

You can put printString into an enum Utility class or Singleton like

public enum TestClass {;
    public static void printString(){
        System.out.println("print");
    }
}

However, from a performance point of view, creating a new object each time is very small compared to the cost of writing a line to the console. The different is notional.

Upvotes: 1

Amit Deshpande
Amit Deshpande

Reputation: 19185

what you can do is use Enum

public enum TestEnum {
    TestEnum;
    public String printString() {
        System.out.println("print");
        return null;
    }
}

There will not be much difference in performance point of view but from coding point of view you will have no need to create object every time. Also you can have static utility class as enum.

Upvotes: 1

Related Questions