I'm creating and translating a few algorithms when I'm wondering which is faster?
a) (int)float
or
b) Mathf.FloorToInt(float)
Thanks in advance.
EDIT: If there is a faster way than either of those, that would be helpful too.
Do a test with Stopwatch like I mentioned. This answer is here because I believe that the result in your answer is wrong.
Below is a simple performance test script that uses loop since your algorithm involves many loops:
void Start()
{
int iterations = 10000000;
//TEST 1
Stopwatch stopwatch1 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
int test1 = (int)0.5f;
}
stopwatch1.Stop();
//TEST 2
Stopwatch stopwatch2 = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
int test2 = Mathf.FloorToInt(0.5f);
}
stopwatch2.Stop();
//SHOW RESULT
WriteLog(String.Format("(int)float: {0}", stopwatch1.ElapsedMilliseconds));
WriteLog(String.Format("Mathf.FloorToInt: {0}", stopwatch2.ElapsedMilliseconds));
}
void WriteLog(string log)
{
UnityEngine.Debug.Log(log);
}
Output:
(int)float: 73
Mathf.FloorToInt: 521
(int)float
is clearly faster than Mathf.FloorToInt
. For stuff like this, it is really bad to use the FPS from the Editor Stats to make the judgement. You do a test with the Stopwatch
. The FPS should be used when writing shader code.