Hello im coding somewhat heavy performance wise thing (that will execute very often) and ive already optimized it in number of ways but i cant tell which option should I go for.
I normally use arrays in performance-important things cause ive read theyre a bit faster. but now my case is a bit special.
The options im considering are:
array.for
array.findall
list.for
list.findall
What I want to do is to:
go through MAIN array of length 100 that contains A. positions, B. subarrrays pick about 10-20 of them (main array elements) that are close to the player for each of these, go through another 100 and calculate distance to player im not sure here, i heard Array.for loop is the fastest
but here the condition is pretty clear (distance to player) maybe array.find all or list.findall are faster here?
Please tell me which option should i go with for both main array and subarrays. thanks
Use Benchmark.NET to find out which one is fastest for your specific case.
while ive tested this issue and went with for loop eventually, heres something that confuse me
LIST FOR 00:00:00.0000980
LIST FOREACH 00:00:00.0000007
ARRAY FOR 00:00:00.0028450
ARRAY FOREACH 00:00:00.0051233
https://dotnetfiddle.net/RKWBJl
it would seem that list forr and foreach are much faster?
Kind of offtopic, but if you working with positions e.g.2D coordinates, have you looked at QuadTrees?
The differences are going to be pretty small, can you do other assumptions about the data (is only the player moving and the rest of the elements position constant?) because any significant gains you could hope for would be algorithmic
I assume you mean Array.ForEACH and List.ForEACH?
They’re all O(n). They couldn’t possibly be anything else (unless your data is sorted). They know nothing of your data, so must linearly loop through each element and test it. Any differences between them will be negligible.
Looping through 2000 (20×100 in worst case) objects should not take any noticeable time at all, so most likely you’re prematurely optimizing here. Meaning, don’t worry about efficiency until you’ve got an actual slowness issue to solve. Our brain is not as nearly as good at predicting what will be slow as just running the program.
It’s hard to say which will be best, because it’s not clear what you want to do with what you find.
That said, be aware that both Array.FindAll
and List.FindAll
will allocate respectively a new array and a new list to hold the results, which might not be what you want. Using LINQ methods might be more efficient, since they allocate less memory.