• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by druphoria · Oct 26, 2015 at 12:01 PM · unity 5performancevectors

How do Vector.Distance and Vector.normalized perform so well despite these operations typically requiring a square root operation?

I've read in multiple different places that square root operations are slow and should generally be avoided within the update loop. However, I've noticed that the Distance and normalization functions on Vector2 and Vector3 perform fairly well and don't seem to cause any problems when I use them in my Update function.

Do these functions actually perform square root operations? If not, what kind of approximations are they using to achieve the same result?

Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by HenryStrattonFW · Oct 27, 2015 at 06:22 PM

Yes, these function are doing square root operations, which is why there are alternatives like squared magnitude and DistanceSquared to get around those slower methods.

However the speed difference will likely be generally unnoticeable unless you are making a lot of calls to them each frame (and I mean a lot) typically there is no problem using the more costly methods and you wont necessarily have to optimize them unless you really start seeing performance issues and need to get every bit of performance you can back.

Comment
Dave-Carlile
druphoria

People who like this

2 Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Eno-Khaon · Oct 27, 2015 at 07:15 PM 1
Share

Adding to this:

As one example of a simple, visual way to see an immediate feedback on this type of operation, you could try something like this:

 using UnityEngine;
 using System.Collections;

 public class OperationTime: MonoBehaviour
 {
     float startTime = 0;
     float endTime = 0;
     int i;
     Vector3 startVector = new Vector3(-2.738f, 5.49985f, 2.070492f);
     Vector3 endVector = new Vector3(7.32086f, 15.38201f, -9.11523f);
     Vector3 normalizedResult;
     float distanceResult;
 
     void Update()
     {
         // normalize 10,000,000 vectors
         if(Input.GetKeyDown(KeyCode.A))
         {
             startTime = Time.realtimeSinceStartup;
             for(i = 0; i < 10000000; i++)
             {
                 normalizedResult = (startVector - endVector).normalized;
             }
             endTime = Time.realtimeSinceStartup;
             Debug.Log("normalize vector:\t\t" + (endTime - startTime));
         }
         // calculate 10,000,000 vector magnitudes
         if(Input.GetKeyDown(KeyCode.S))
         {
             startTime = Time.realtimeSinceStartup;
             for(i = 0; i < 10000000; i++)
             {
                 distanceResult = (startVector - endVector).magnitude;
             }
             endTime = Time.realtimeSinceStartup;
             Debug.Log("magnitude:\t\t" + (endTime - startTime));
         }
         // calculate 10,000,000 vector magnitudes (alternate)
         if(Input.GetKeyDown(KeyCode.D))
         {
             startTime = Time.realtimeSinceStartup;
             for(i = 0; i < 10000000; i++)
             {
                 distanceResult = Vector3.Distance(startVector, endVector);
             }
             endTime = Time.realtimeSinceStartup;
             Debug.Log("magnitude (Vector3.Distance):\t" + (endTime - startTime));
         }
         // calculate 10,000,000 vector square magnitudes
         if(Input.GetKeyDown(KeyCode.F))
         {
             startTime = Time.realtimeSinceStartup;
             for(i = 0; i < 10000000; i++)
             {
                 distanceResult = (startVector - endVector).sqrMagnitude;
             }
             endTime = Time.realtimeSinceStartup;
             Debug.Log("sqrMagnitude:\t\t" + (endTime - startTime));
         }
     }
 }

You might be surprised at how quickly and slowly some things are processed.

avatar image

Answer by starikcetin · Oct 27, 2015 at 08:21 PM

These kind of suggestions are for developers whose aim is to "maximize" the performance. That differences won't even be visible to human eyes.

Comment

People who like this

0 Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Eno-Khaon · Oct 27, 2015 at 08:36 PM 1
Share

True. In the grand scheme of things, it likely won't make a big difference.

However, that doesn't automatically discredit their use.

While it certainly doesn't apply to all games, there's no harm in finding ways of improving what you have. For example, if you take a look at tag comparison vs. layer comparison,

 if(gameObject.tag == "ThisTag")

is slower than

 if(gameObject.CompareTag("ThisTag"))

is much, much slower than

 if(gameObject.layer == thisLayer)

This is a question and answer combination which can lead to various optimizations and, while some might argue that there's no need to optimize in the beginning, the first step to optimization is to know what you can do and when.

Just because something is slower, that doesn't mean it needs to be your first choice.

avatar image starikcetin Eno-Khaon · Oct 27, 2015 at 08:41 PM 0
Share

I haven't mentioned that they are useless, I respect the suggestion. But for the early stages of development, people shouldn't force theirselves to maximize performance, that's a thing they get around later imho.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

6 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Good way to convert an int to a string each frame? 1 Answer

Does Debug.Drawray affect performance in the build? 1 Answer

What faster? Make a saved scene with gameobjects, or create it on start? 1 Answer

Is it just me or is performance is Unity 5 very poor? 3 Answers

Moving many static colliders - Bad performance 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges