• 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
0
Question by jakejolli · Mar 09, 2015 at 11:55 AM · c#performancenullreferenceexception

Cost of null references during runtime

Are null reference exceptions expensive during runtime (do they cause lag)? I assume that these are handled by Unity, thus the nice debug message, but I was wondering if I should bother checking that certain references are not null before trying to carry out some action with them in order to improve performance, or would that be a waste of time?

For example, if I'm getting a component from a RayCastHit, should I bother checking that the hit is on a certain object that I know has the component, or should I even bother?

I know its as simple as adding something like

 if (someObject.GetComponent<someComponent>() != null){
      someObject.GetComponent<someComponent>().doSomething();
 }

but should I even bother, or just let Unity handle it?

Comment
Add comment · Show 4
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 abi-kr01 · Mar 09, 2015 at 12:47 PM 0
Share
 if (someObject.GetComponent()){
 someObject.GetComponent().doSomething();
 }

avatar image fafase · Mar 09, 2015 at 12:48 PM 0
Share

This is not doing anything else. Just less typing but the compiler will add the missing parts.

avatar image Landern · Mar 09, 2015 at 12:53 PM 0
Share

@fafase is spot on, unity objects have an override for the operator '==' and Equals method that allows the object to return true/false depending if it's null internally or not.

@jakejolli, checking for null is almost free and considered one of the least expensive operations you can get in c#/.net. You should always check for a component if you're not sure whether the object you're referencing is instantiated(some say you should do it anyways).

Also if you can cache an object reference in a script, you should do so if it makes sense in the context of your game. That way you're not calling GetComponent or GameObject.Find in updates which can bring the performance of your game down.

avatar image fafase · Mar 09, 2015 at 01:00 PM 0
Share

.NET 6 brought the Safe Navigation Operator (roooh sounds fancy):

 object?.member;

but it is not for Unity yet...

2 Replies

· Add your reply
  • Sort: 
avatar image
3
Best Answer

Answer by fafase · Mar 09, 2015 at 12:50 PM

There is no concern to have on null checks, there are micro optimisation that will not affect your app in the end.

On the other hand, this could:

 someComponent comp = someObject.GetComponent<someComponent>();
 if (comp != null){
      comp.doSomething();
  }

in your case you are running GetComponent to check if the component is there and then you call it again to perform the action. In my case, I call once and do both actions.

Your game does not crash in Editor because Unity prints the debug and keeps going with some workaround, but if you run on device, it will most likely crash or freeze.

The short answer is "You HAVE to avoid null references".

Comment
Add comment · Show 6 · 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 Landern · Mar 09, 2015 at 12:56 PM 0
Share

or to look at it another way. If you're calling a friend to get a ride, should you call the friend, ask if their there, then hang up, call again and finally ask if you can get a ride?

Once you get a reference to the object, you don't need to call GetComponent over and over again as there is a cost associated with the look up for the component. As long as the scope doesn't change, you should be fine using the same reference over and over again as fafase illustrates above.

avatar image jakejolli · Mar 09, 2015 at 01:06 PM 0
Share

@Landern I think my question may have been misunderstood. I'm not asking how expensive it is to check if something is null, I'm asking how expensive it is to attempt to do something with a null reference (which might occur if I don't check for null.)

avatar image fafase · Mar 09, 2015 at 01:08 PM 0
Share

Well, you get a null reference exception and a crash of your app. So I don't know how much you value an unsellable app but that is what you get.

avatar image jakejolli · Mar 09, 2015 at 01:48 PM 0
Share

$$anonymous$$y game doesn't crash, I just get an error in my console... But I'm guessing that the short answer is: "Yes, you should avoid null references"?

avatar image fafase · Mar 09, 2015 at 01:51 PM 0
Share

Your game does not crash in Editor because Unity prints the debug and keeps going with some workaround, but if you run on device, it will most likely crash or freeze.

The short answer is "You HAVE to avoid null references".

Show more comments
avatar image
0

Answer by HHess · Mar 01, 2019 at 10:24 AM

JetBrain's Ride warns using the null checks in 'performance critical context' https://github.com/JetBrains/resharper-unity/wiki/Avoid-null-comparisons-against-UnityEngine.Object-subclasses

Comment
Add comment · 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 Bunny83 · Mar 01, 2019 at 03:23 PM 1
Share

This should be considered a bug in the resharper. The custom == operator first does an actual null check on the managed side. Note that there is a huge difference if you run code inside the editor or in an actual build. For example inside the editor methods like GetComponent will always return an actual object in order to show a specialized error message. However in an actual build GetComponent will return null. An actual null value is treated perfectly well by the custom == operator. The only cases where it has an impact is when you actually destroyed an object where you still have a reference to. This will turn the object into a fake null object and may cause the == operator to actually check on the native side.


Though as you can see here if the reference is a $$anonymous$$onoBehaviour or a ScriptableObject this isn't really an issue.


Apart from that if you actually have situations where you can encounter null references you have to check for them, otherwise your application will just crash. The exact behaviour depends on the platform, but even if it doesn't crash it will throw an exception which is by far worse than having Unity check if the object is still alive. Note that Apple will reject any app that throws uncatched exceptions.

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

24 People are following this question.

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

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

IL2CPP Unused local just for stack balance error 0 Answers

Flip over an object (smooth transition) 3 Answers

NullReferenceException error in an array of objects 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