# Optimizing for memory with images

**URL:** <https://discourse.processing.org/t/optimizing-for-memory-with-images/25772>\
**Category:** Coding Questions\
**Created:** [November 27, 2020, 7:17pm UTC](https://discourse.processing.org/t/optimizing-for-memory-with-images/25772 "2020-11-27T19:17:57Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![josephh](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/josephh/32/210_2.png) [@josephh](https://discourse.processing.org/u/josephh)\
**Post date:** [November 29, 2020, 5:14pm UTC](https://discourse.processing.org/t/optimizing-for-memory-with-images/25772/9 "2020-11-29T17:14:33Z")

</div>

Hi,

> [@SheCurvesMobius](#):
>
> Thanks once again for your response–I can feel my brain starting to make fundamental shifts around how I can structure the code.

I can clearly see that it’s starting to make sense!

> [@SheCurvesMobius](#):
>
> Is that correct?

Indeed it’s exactly what I (and others, @micycle @noel ) were suggesting. 😉

Note that the garbage collector is not instantly releasing a previous overwritten `PImage`. It’s up to the JVM (Java virtual machine, running the bytecode produced by the Java compiler) to decide when to free the previous image. Anyway it’s going to greatly reduce memory usage!

I found those useful StackOverflow links about garbage collector and how to deal with it :

- [garbage-collector-in-java-set-an-object-null](https://stackoverflow.com/questions/5690309/garbage-collector-in-java-set-an-object-null)

- [force-jvm-to-free-memory](https://stackoverflow.com/questions/54267714/force-jvm-to-free-memory)

- [what-the-frequency-of-the-garbage-collection-in-java](https://stackoverflow.com/questions/12599044/what-the-frequency-of-the-garbage-collection-in-java)

For your last question, this is just a question of clarity and style because this is equivalent in terms of result. For future code readers, you can add comments but at this point of the project is probably not necessary.

If you were worried about memory for creating an intermediate variable, you are creating it in a for loop, therefore it’s in a local scope meaning that as soon as you go out of the block (at the next iteration), the object can be freed from memory by the garbage collector. And also thousands of `String` is not that much.

---

_[View the full topic](https://discourse.processing.org/t/optimizing-for-memory-with-images/25772)._
