my dog learned polymorphism
The moose likes Beginning Java and the fly likes create object vs. casting list obj (performance) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "create object vs. casting list obj (performance)" Watch "create object vs. casting list obj (performance)" New topic

create object vs. casting list obj (performance)

Hosh Nasi
Ranch Hand

Joined: Sep 10, 2004
Posts: 44
What is the performance diffrence of casting a List object to creating a new Object.

It seems to me that even though your using an objects refernce your still creating a new interface.

What is the diffrence between this:

and this:

in my particular application I know the index of the List so I will not need to slow this down with an iterator.

Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

You can't create a new interface - pedantic speaking.
But talking about these things, we need to be pedantic.

When you cast an element from a collection, you don't create a new object - or a new instance, but get exactly that object, which was put into the collection (or added or inserted...).

That is in first place a question of semantic.

will give you an element from the list.

(you made a syntax-error at this point in your code)
will give you something.

For performance:
a) There is a well known saying from old Guru Knuth:
premature optimization is the root of all evil.
b) c) d) -> see a)

e) Constructor call's aren't gratis.
f) How many casts do you need per second?
It will depend on your machine, on the jvm, on the rest of the program.

g) Make some test.
If your machine isn't state of the art, 10 Million casts could be enough to show a small difference to a constructor-call.
But you have to make many tests, and run as well with identical values, as with different ones, to exclude circumstances influence your measures (foreign programs running in the background, consuming cpu, caches holding something in memory and so on).
And a solution performing well for 100 cases may perform lousy for 200.

But in real life, you can't choose.
If you could go without the list, why use a list at all?
I agree. Here's the link:
subject: create object vs. casting list obj (performance)
It's not a secret anymore!