If I have a function that needs very fast (down to instructions level) access to a few variables in a struct, how should I do it?
The program in question is an interpreting emulator. The fetch/decode/execute function needs very fast access to the (emulated) registers.
The logically correct way to do this would be to use a context struct (C style) or have them as member variables and function (C++ style).
Code:
struct Context {
int regs[16];
}
void f(Context *ctx)
{
// do stuff with ctx->regs[]
}
...
Then
Context ctx;
f(&ctx);
However, that means all accesses to regs need to go through at least a layer of redirection (de-referencing ctx).
Or in C++
Code:
class C
{
int regs[16];
...
void f()
{
// do things with regs[]
}
};
which will compile to exactly the same thing (except ctx would be called "this").
A more efficient way is to make them static
Code:
void f()
{
static int regs[16];
// do things with regs[]
}
This way would save a de-reference.
However, that's ugly. Is there a way to get best of both worlds? Somehow "instantiating" code?