Unity3D: Vector3 – magnitude vs sqrMagnitude

The Unity Script Reference states that Vector3.sqrMagnitude is “much faster” than .magnitude, however it doesn’t say by how much. I use it for testing the distance between two objects to see if one is in range of the other (by subtracting one Transform’s position from the other, then finding the magnitude), and when you have many objects to test, it would be wise to use the fastest method. I did a couple of tests on my PC and smartphone and here are my results:

PC (Intel Core i5, 10 million executions per run per function, averaged result over 10 runs)

sqrMagnitude: 2853 ms. (96.13% of magnitude’s time)

magnitude: 2968 ms. (104.03% of sqrMagnitude’s time)

 

Android (Samsung Galaxy S II, 10 million executions per run per function, averaged result over 10 runs)

sqrMagnitude: 6155 ms. (77.11% of magnitude’s time)

magnitude: 7982 ms. (129.68% of sqrMagnitude’s time)

After averaging all the runs on PC the two results are very similar, although sqrMagnitude is definitively faster, albeit by only 4%. On my phone the numbers are much more dramatic, with a time saving of almost 23% when using sqrMagnitude instead of magnitude.

It’s unlikely that you will need to worry about this unless you are developing for mobile or you are using these functions over 10,000 times per frame on PC. If you are developing for mobile or you have any efficiency worries or drop in framerate and you use these functions 1,000s of times per frame or more, then it would be wise to use sqrMagnitude over magnitude. Of course, you will also have to change your comparison values to their square equivalents or you won’t get the same functionality.

Advertisements

~ by Daveoh on May 2, 2013.

One Response to “Unity3D: Vector3 – magnitude vs sqrMagnitude”

  1. Cool? Thanks)

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: