0

In Lua, it is slightly faster to put a function you call often from a global math library. For example:

local variable = math.sin

Instead of math.sin(x), you would now use it as variable(x) (bad naming used for demonstration purposes).

Well, what about C#? Imagine you want to call method Class.method() one million times. I assume it would be faster to put that method inside a variable, but how would I do that?

In my case, I am calling function Mathf.PerlinNoise thousands of times relatively frequently and I would like to put it inside a variable.

How do I do that and should I even bother? How much can this affect performance in extreme cases (tens of millions of calls for example)?

FICHEKK
  • 749
  • 1
  • 6
  • 24
  • 3
    Don't assume, know. In this case, measure performance. Go find an example using BenchmarkDotNet and use it to measure performance with and without that variable. In .NET this is called a Delegate, you can find many examples on the internet. I can tell you the outcome though, the static method call is going to be fastest, not by a huge margin, but still fastest. But don't take my word for it, learn how to measure things like this, it's a skill that is good to have. – Lasse V. Karlsen Jul 31 '18 at 19:03
  • 1
    Methods can be stored as delegates. I would strongly suggest not putting methods in variables when you can already access it from where it's supposed to be. If you need to select from a list of possible methods to use, you can put a bunch of delegates into a dictionary and execute one or the other. I'm not particularly aware of any performance difference, but I figure it won't be much and this seems like it will increase the confusion and complexity of your project unnecessarily. – EMUEVIL Jul 31 '18 at 19:06
  • Looks like `Mathf.PerlinNoise` has a signature of `(float -> float -> float)`, so `Func perlinNoise = Mathf.PerlinNoise;` should get you an anonymous delegate to the function. Is that what you're looking for? – Jonathon Chase Jul 31 '18 at 19:07
  • This is NOT a duplicate of https://stackoverflow.com/questions/7367152/dynamically-assign-method-method-as-variable. The suggested duplicate doesn't speak to performance/optimization at all. – Ted Bigham Jul 31 '18 at 19:16
  • In Lua what you are really doing is _G['math']['sin'](x). This requires a lookup in the __index metamethod on _G for 'math' that returns a table, then another on that table that returns the function then the function call. In C# the compiler just uses the address of the function directly, there is no meta method type lookup for statics like this, so storing it in a local variable wont make a difference. – Simon Smith Jul 31 '18 at 21:07

0 Answers0