Reputation: 255
I'm making a game where I need to tell how many cars are contacting the player's car, and which cars. My plan is to create a List
, and add and remove cars when necessary.
Here's my question. My Car
class is very expensive to create (processing power wise). How expensive is it to create a reference to a car? I know in C++ what I'm talking about is called a pointer. Here's an example in code:
Car newCar = new Car(); // expensive
Car carCopy = newCar.clone(); // expensive
Car referenceNewCar = newCar; // expensive?
referenceNewCar
should point to the same place in memory as newCar
, right? So it won't have to initialize anything, and saying newCar.changeMemberVariableTo(1)
is the same as referenceNewCar.changeMemberVariableTo(1)
; either way, newCar
and referenceNewCar
are both affected, because they point to the same place in memory.
I assume it would be cheaper to create a new reference than an entirely new Car
. How much faster is it? If it takes, say, 3 seconds to create a new Car
, will creating a new reference to the same car be nearly instantaneous?
Thanks in advance.
Upvotes: 3
Views: 154
Reputation: 1500893
Copying a reference from one variable to another is very cheap. It's likely to be as cheap as copying an int
or long
value (depending on a few things about the JVM in question).
All you've got is two variables with exactly the same value - a reference. That value will be very small (4 or 8 bytes under most implementations) and copying it doesn't usually require any more effort than copying the bytes.
(I've a sneaking suspicion that some JVMs may be a little bit cleverer than this; for the sake of garbage collection, it's possible that some JVMs update flags about the oldest generation which has a reference to a particular object, for example - but that will vary by implementation, and my memory may be wrong anyway.)
Upvotes: 2