Regarding creating new objects in a short time

60 Views Asked by At

I'm using JDK-21 and i'm trying to create an A.I. system for a MMORPG game. I prefer writting code using stream/Optional that is available within java library rather than if/for.

My code execute every 400ms for a big number of A.I. players. This mean 400-500 players can execute around 20 Optionals per 400 ms. This mean java create 4.000 Optionals objects per 400 ms. Is this bad? Will this cause issues later on? Garbage collector can handle this task? I'm overthinking sometimes that making such complex codes using Optionals and generate more and more can lead into RAM issues later on.

I prefer write using this way

1

There are 1 best solutions below

2
On BEST ANSWER

I prefer write using this way

And you should. Modern garbage collectors are heavily optimized for the use case of creating a bunch of short-lived objects. That's because the JVM's garbage collector (and, indeed, most garbage collectors these days) is generational. A generational garbage collector runs on the assumption that most objects being created in the system are either (a) extremely short lived, or (b) extremely long lived.

There's at least two separate generations in the garbage collector. For simplicity, I'll assume there's only two (This seems to indicate that there's several, but that page is also fairly old)

  • All new objects are created in the "young" generation. The young generation is a smaller pool of memory and is cheap to construct and free. Most objects live very short lives in this generation. The "young" generation is relatively small and can be garbage-collected cheaply.
  • If an object survives enough "young" garbage-collections, it moves to the "old" generation. The "old" generation consists of longer-lived objects which are less likely to be freed. If a "young" garbage collection doesn't free enough memory, we'll go free the "old" generation next, which is a slower operation.

So to directly answer your question: Create short-lived objects to your heart's content, and trust that a high-level language like Java is smart enough to do smart things with your code. If you later discover (through profiling and benchmarking tools) that a particular hot code path is a bottleneck, then (and only then) you can talk about switching to lower-level constructs and eliminating allocations. But doing so now would be a premature optimization.

Related questions: