C# Int to Float conversion performance

What is the performance of int to float casts in C#. I'm looking at the lightning example from Unity Procedural Examples, and there are two int -> float casts inside the tight loop. My understanding is these casts are quite slow in C, What is the performance of these casts in C#?

I'm curious about both int->float and float->int.

Here is the code from the lightning example:

for (int i=0; i < particles.Length; i++)
{
    Vector3 position = Vector3.Lerp(transform.position, target.position, oneOverZigs * (float)i);
    Vector3 offset = new Vector3(noise.Noise(timex + position.x, timex + position.y, timex + position.z),
                                noise.Noise(timey + position.x, timey + position.y, timey + position.z),
                                noise.Noise(timez + position.x, timez + position.y, timez + position.z));
    position += (offset * scale * ((float)i * oneOverZigs));

    particles*.position = position;*
 _particles*.color = Color.white;*_
 <em>_particles*.energy = 1f;*_</em>
<em>_*}*_</em>
<em>_*```*_</em>

Put this in front of the code:

float timer = Time.realtimeSinceStartup;

and this after it:

Debug.Log (Time.realtimeSinceStartup - timer);

Then compare times with and without the cast.

Not that I disagree with Eric's suggestion, but there's a built-in profiler option that I think more people should know about.

http://unity3d.com/support/documentation/ScriptReference/Profiler.BeginSample.html

Profiler.BeginSample ("MyPieceOfCode");
// do something that takes a lot of time
Profiler.EndSample ();

Then in the profiler you can see it referenced by name.

Of course this doesn't work on Unity iPhone as there's no profiler.

I fixed a few things in this code:

  • reduced the two int to float casts to one
  • I moved the color and energy initialization into Start()
  • reduced the amount of lookups by storing target.position and trasform.position in local variables
  • I removed one float multiply by storing the product of i and oneOverZigs in a local variable

The final code which is roughly 18% faster is as follows:

Vector3 targetPos = target.position;
Vector3 myPos = transform.position;
for (int i=0; i <  particles.Length; i++)
{
    float f_i = (float)i;
    float dist = oneOverZigs * f_i;
    Vector3 position = Vector3.Lerp(myPos, targetPos, dist);
    Vector3 offset = new Vector3(noise.Noise(timex + position.x, timex + position.y, timex + position.z),
                                noise.Noise(timey + position.x, timey + position.y, timey + position.z),
                                noise.Noise(timez + position.x, timez + position.y, timez + position.z));
    position += (offset * scale * dist);

    particles*.position = position;*
*}* 
*```*