I need to optimize this few lines of code, it’s works fine but a feel that i can get it to be more efficient. Is there a way to get it using linq or whatever? Thanks.
public List<ItemSO.Recipe> GetRecipeList()
{
List<ItemSO.Recipe> list = new List<ItemSO.Recipe>();
foreach (GameObject item in m_items)
{
ItemManager component = item.GetComponent<ItemManager>();
list.Add(component.m_itemData.m_shared.m_recipe);
}
return list;
}
Linq in almost all cases is not an optimisation at all. Linq just allows to achieve the same result with less code but in most cases with worse performance and memory footprint. So the term “optimise” is just wrong in that case ^^.
There are two actual optimisations you can / should do in your case. First of all since all your “items” seems to have an ItemManager component, you want to change your “m_Items” list / array from the type GameObject to the type ItemManager. So your list already contains the instance references to the ItemManagers of all those items. Unity can serialize those the same way…
The second point that most people forget when they create a new list is to specify the initial capacity. In a lot of cases it’s not possible to choose a meaningful capacity so having the list grow as needed is the best solution in such cases. However when you know beforehand how many items you’re going to add to the list, you should specity the capacity when you create the list. In your case:
var list = new List<ItemSO.Recipe>(m_items.Count);
if your “m_items” is an array, of course you would use “Length” instead of “Count”. Other than that your code is already optimised.
Though if you’re not looking to optimise your code but just to shorten the code by using Linq, you can do:
public List<ItemSO.Recipe> GetRecipeList()
{
return m_Items.Select(item=>item.GetComponent<ItemManager>().m_itemData.m_shared.m_recipe).ToList();
}
Since we now have support for the => operator for methods we can even do:
public List<ItemSO.Recipe> GetRecipeList() => m_Items.Select(item=>item.GetComponent<ItemManager>().m_itemData.m_shared.m_recipe).ToList();
Though as I mentiond this will have a way worse performance than your original code. It’s also harder to read and much more difficult to debug in case you have an issue. So I would highly recommend you stick with your original code and apply the actual optimisations I mentioned above.