• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous Objects

 
Didier Varon
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have been using the following syntax:

HttpServletRequest request;
int userID = (new UserUtil(connection)).findByUserName(request.getRemoteUser()).getUserID();

I know that is not the cleanest code to read, but I have the idea that is efficient, because there are not new references created on the heap, then the anonymous object is ready for garbage collection. Now if I do something like:

HttpServletRequest
UserUtil userUtil = new UserUtil(connection);
String userName = request.getRemoteUser();
User user = userUtil.findByUserName(userName);
int userID = user.getUserID();

will be as efficient that the code describe first?
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That code doesn't look like if it was 100.000 times per minute, so I guess you don't earn to much performance-improvement from it.

Without seeing sourrounding code, it's not possible to say much about the possibility of GarbageCollection to profit from an anonymous Class.

Usually it's a bad idea to help the garbage-collector.
People who liked to help it often fail to show a real-world example, which is impressing.
I'm not impressed so far.
How big is that UserUtil?

Impress me!

Isn't that code-block left shortly later although?
 
steve souza
Ranch Hand
Posts: 862
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There would be no measurable difference. The objects will become eligible for collection when they go out of scope.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Steve and Stefan - don't worry about it, just use the one that you find easier to read.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, all objects are "anonymous" in the sense that they don't have names. The only things having names are the reference variables (which an object can have an arbitrary number being referenced by).
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13071
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now think about this - suppose you got a null pointer exception from the line

How would you inform the operator or the user what the problem was?
Veterans of this forum know whats coming next.

Premature optimization is the root of all evil

Do a search for that phrase in Google

Bill
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic