Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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 CloverKitsune · Nov 08, 2012 at 08:55 PM · c#javascriptarrayloopforeach

Checking an array variable in C# vs JavaScript

I'm new to Unity and C# (I must learn C# to work with some people), but the best tutorials guiding from basics to game creation I've found only cover JavaScript, so I've been following along, translating JavaScript to C# where needed.

When it came time to create an IF statement checking on an item in a string array, I ran into a problem. The JavaScript code works like this:

     var inventory = Array("food", "gun", "ammo");
     if ("food" in inventory)
         print("You have found " + inventory[0]); 


The closest equivalent I could find (most resources are full of technical terms I don't yet understand) is C#'s "foreach," which looks like this:

 string[] inventory = {"food", "gun", "ammo"};
     foreach(string myItems in inventory)
         {
         if(myItems == "food")
             print("You have found " + inventory[0]);
         }

Is that a suitable way to do it? I heard that foreach is a loop (not sure if the JavaScript use of "in" is too), so I wasn't sure if that meant it just keeps going on and on in the background, taking up resources or something else inefficient. All I wanted to do at the moment was check on a string in an array.

Comment
Add comment · Show 1
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 valyard · Nov 10, 2012 at 09:40 PM 0
Share

It is a good practice to accept answers or at least upvote them.

3 Replies

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

Answer by Landern · Nov 08, 2012 at 09:27 PM

 string[] inventory = {"food", "gun", "ammo"};
     foreach(string item in inventory)
        if(item == "food")
          print("You have found " + item);


item carries the value of the current item from the inventory collection. This is suitable for display as it is just a string.

Comment
Add comment · 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
0

Answer by valyard · Nov 08, 2012 at 09:25 PM

The misconception here is because in JavaScript Object and Array don't differ much. The later has length property but you can interchange them freely. In c# Arrays are more like good old arrays in C. But they have lots of extending methods like IndexOf for example. They are basically doing the same as your code does internally but at least your code gets cleaner.

Also you may want to look at List and Dictionary types. Which are more powerful and have better search time than arrays.

Comment
Add comment · Show 5 · 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 · Nov 08, 2012 at 09:34 PM 0
Share

arrays perform better then a List does, it's memory foot print is also smaller with the same type because the object graph is smaller.

That said, List/Collection/Hashset/Dictionary are superduper awesome functions

so if you have a set collection that you know the length/count of, use an array, unless you need the extension methods for list and such

avatar image valyard · Nov 08, 2012 at 09:39 PM 0
Share

Perform better where? It is still O(n) to look for a specific element.

avatar image Eric5h5 · Nov 10, 2012 at 09:54 PM 0
Share

Array access is significantly faster than List access for primitive types (not so much for things like GameObject). Search time is equal; Lists are really just arrays anyway with "extra stuff" that can make them easier to work with for some things.

avatar image whydoidoit · Nov 10, 2012 at 10:15 PM 0
Share

Just to add to Eric's point - if you inspect a List in the debugger you will see it actually contains an array which is what is used to get the data. Lists allocate arrays of extra size and when they fill up, it allocates another bigger array - these will increase in size based on how many times you add things to them.

If you are vaguely aware of the O notation then:

Arrays are O(1) for indexed access, Dictionaries and Lists approach O(1) performance for accessing an item by index with lists being faster (and dictionaries not necessarily using an integer index). This basically means that it doesn't matter how many things there are in the collection, the access time will be the same.

However finding a thing in a List or an Array by its value is an O(n) operation - dependent on the n number of things in the list (in other words slow and probably not scalable). The time to access something in a SortedList using binary search is O(log n) - (read much much faster) at the penalty of inserting something into the list being slow (so good for many searches and few writes). You will probably never use a SortedList though unless you really need sorted data because of Dictionaries being O(1) for finding an item based on a particular value.

So just to reiterate, Dictionaries are fantastic at finding things by the key value (which of course isn't necessarily an index integer) where they are O(1) - it doesn't get more scalable than that.

avatar image whydoidoit · Nov 10, 2012 at 10:17 PM 0
Share

Lists are perfect for non-sparse (not many values are empty) integer indexed items that may grow.

Arrays are perfect for non-sparse integer indexed items that do not grow.

avatar image
0

Answer by digitalfront · Nov 08, 2012 at 11:09 PM

If you use Lists with System.Linq you can do searches like this myList.Where(item => item == "food");

I'm sure it adds some overhead, but might be worth it.

Comment
Add comment · 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

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.

Follow this Question

Answers Answers and Comments

14 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

Related Questions

Array Element in Foreach loop 1 Answer

Using ForEach Loop to change variables on prefabs 1 Answer

Saving and applying an array of Vector3 velocities on an array of GameObjects 1 Answer

I have to set a Collider[] to Collider - what do? 1 Answer

Multiple Cars not working 1 Answer


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