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
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)
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: