java - Create new object vs setting its variables inside a function -


i have rectangle class , constructor sets every variable (x, y, width, height) specific value. after rectangle being created, if want change of values. that, more efficient have function rect.set(newx, newy, newwidth, newheight); or call constructor r1 = new rectangle(newx, newy, newwidth, newheight); on again ? (since won't referencing older rectangle anymore)

public rectangle (int x, int y, int width, int height) {     this.x = x;     this.y = y;     this.width = width;     this.height = height; }  public void set (int x, int y, int width, int height) {     this.x = x;     this.y = y;     this.width = width;     this.height = height; } 

i imagine creating new rectangle create garbage, should worse. true ? or java somehow optimize ?

this rather old question. highly dependent on task.

of course, creating object has overhead comparing mutating existent object, in cases negligible. overall creating new objects preferable way design point of view.

hotspot jvm (desktop) highly optimized creating large amounts of short-lived objects.

read more: https://softwareengineering.stackexchange.com/questions/149563/should-we-avoid-object-creation-in-java

however, on other platforms, such android, excessive object creation can lead noticeable gc pauses, should avoided, especially in game development.

upd

from gathering scraps of information across comments can conclude:

  • you writing game android
  • you have one logical rectangle instance @ each moment of time
  • you modifying large number of times (probably in cycle within method)

in these conditions reasonable approach mutate single instance of rectangle.

rationale:

  • avoid gc pause on android
  • encapsulate mutated rectangle instance in method/class (it's ok violate design practices in performance-critical spots long these spots encapsulated , know doing)

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -