Hey everyone!
I am wondering, is it possible to somehow define some lines of code and place those all over the place?
- I know I can call a method. But this has overhead.
- I know I can try aggressive inlining, but that’s not guaranteed to inline.
- I know I could use snippets, but I cannot modify all instances conveniently.
I’d like something like this:
#define WAIT60_30
if (waitType == WaitType.Fps60) {
yield return fps60;
}
else {
yield return fps30;
}
#enddefine
[...]
enum WaitType {Fps60,Fps30};
WaitType waitType;
YieldInstruction
fps60 = new WaitForSeconds(1.0f/60.0f),
fps30 = new WaitForSeconds(1.0f/30.0f);
IEnumerator Anim () {
while (true) {
// do stuff
#WAIT60_30
}
}
Something like that would be great in both C# as well as for (Compute)Shaders.
Best wishes,
Shu
Short answer: no. The C# preprocessor does not support full macro interpolation the way C/C++ does.
I’m sure you could cobble together some janky asset import script which did this kind of thing. But honestly, just no. Your example is allocating an IEnumerator anyway, so any really “aggressive” inlining gains is pretty much toast.
1 Like
If you mean like macros, no you can’t define macros.
C# supports preprocessing directives, but only for the conditional compilation, not the code itself.
You can either:
- make a function (with aggressive inlining)
2a) make a static library with a static function (that is likely to be inlined, or you can as well force it)
2b) make a static library with an extension method (could be useful, depending on your use exact case)
- make a static local function (which will be inlined, but this goes against “all over the place” requirement)
That’s as far as static code goes.
1 Like
Thanks for your replies, @halley1 and @orionsyndrome ! Those are very informative!
I used an IEnumerator for an example where I couldn’t even find a solution using methods, because I’d have to run a coroutine instead of inserting a snippet, which would require allocating one, so there should be even more of a gain in terms of performance when inlining (?), I guess. But anyway, most of my use cases would indeed be static extension methods that I already have implemented and I absolutely want to inline them, because I may very well run them a few million times in tight loops. But I guess I’ll just have to mark them for aggresive inlining and hope for jit to do that! And for shaders, oh well, I’ll just duplicate code manually, I guess, then.