LWJGL 3 : StackGet() usage

Viewed 91

I've always wondered if I'm using stackPush() and stackGet() correctly. Currently, if I have to use stack, I will first make something like:

try (var stack = MemoryStack.stackPush()) {
...
}

Then, if i'm calling a method within the try block, I will use stackGet() to avoid passing the stack in the parameters of the method:

try (var stack = MemoryStack.stackPush()) {
foo();
}
...
void foo() {
var stack = stackGet();
...
}

I don't find any real explanation about stackGet() on the javadoc, so am I correctly using this function? Does someone can explain me the difference between stackPush() and stackGet() if I'm wrong?

1 Answers

LWJGL 3's MemoryStack holds a fixed amount of off-heap (native) memory per thread as a ThreadLocal variable. The static method MemoryStack.stackPush() will do a ThreadLocal lookup of the per-thread instance of MemoryStack via MemoryStack.stackGet() followed by an instance method call to MemoryStack.push(). And as a result of stackPush() you will simply be given the already looked-up thread-local instance of MemoryStack for your calling thread.

For optimal performance, you should therefore "drag" this MemoryStack instance into other methods and avoid calling MemoryStack.stackGet().

However, it might be possible, that the JVM (within its inline boundary) will optimize multiple calls to MemoryStack.stackGet() (or rather the thread-local lookup therein) to a single lookup at the beginning, since no other thread could have altered the calling thread's thread-local value.

Related