2

I have one class named Sample which is used in my code like below:

class Sample{
 .
 .
 Object someMethod(){
  return someObject;


 }
 .
 .
}

I call itlike:

Object ob = new Sample().someMethod();

I want to know if there is any advantage if I create anonymous ``Objectof any class (new Sample()) and call anyrequiremethod if I don't have any further use of thisObject`.

double-beep
  • 5,031
  • 17
  • 33
  • 41
mcacorner
  • 1,304
  • 3
  • 22
  • 45
  • 1
    I guess such object will *immediately* become a Garbage Collection candidate. I just do not see a clear use case here. – PM 77-1 Jan 07 '15 at 04:38
  • Do whichever one you think is more readable. – ajb Jan 07 '15 at 04:40
  • 5
    An anonymous object could be used to represent/hold any data in your program but if/once it has no further use, the Garbage Collector will clean it up from memory.. This frees up the memory allocated to it.. – Zuko Jan 07 '15 at 04:41
  • I am not taking about readability. – mcacorner Jan 07 '15 at 04:41
  • Is there any advantages If I do the same. – mcacorner Jan 07 '15 at 04:48
  • 2
    Readability _is_ an advantage/benefit. If you're concerned about performance, then say "performance". If you're concerned about memory, then say "memory". When comments indicate that what you've said isn't entirely clear, don't simply repeat yourself by way of elaboration. – Ted Hopp Jan 07 '15 at 04:50
  • 2
    In this case readability is pretty much the _only_ advantage one way or another. Any other difference (in performance, memory usage, etc.), is too small to matter. – ajb Jan 07 '15 at 04:56
  • 3
    While not so much of an advantage in this small case, another potential benefit to such a statement would be in the application of the [Builder Pattern](http://en.wikipedia.org/wiki/Builder_pattern), where you potentially have a class with methods taking many parameters, each with possibly several overloaded variants. The advantage of syntax in which you have "anonymous" objects is that you don't have several lines of code to call several different methods to produce an object, you can "chain" the calls on a single line and "build" the object with the final method call (typically `.build()`) – Ryan J Jan 07 '15 at 05:43

1 Answers1

5

I assume that you are asking about the code you posted as contrasted with the following:

Sample s = new Sample();
s.someMethod();

(where you explicitly assign new Sample() to a local variable).

There's no significant performance or memory benefit one way or another. If you store a reference in a local variable and then invoke the method, I suppose that there may be an (extremely) small performance penalty for storing the reference. However, I suspect that many compilers would notice that the variable is dead once the method is called and would optimize away the assignment. A JIT compiler might finish the job. But we're talking a few cpu cycles at the most.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521