Custom switch-case as an alternative to foreach

foreach switch case javascript
switch case c#
switch case with multiple conditions javascript
javascript switch case
php switch case multiple values
switch statement example
php switch multiple case
foreach switch c#

For a game I am currently working on a particle system. Particles are objects with only position data. These particles have a method that update their position by using a vector field they are embedded into. The particles are inside an array

To update all particles in one physical step, I currently use a foreach:

foreach (particle p in ParList) p.update;

Where the update method is just doing two bitshifts and two additions to the original position. Now I wonder how many particles my system can handle and if I can optimize it to raise that number.

Looking into how foreach works, I found it is just a basic for loop, with doing a comparision and an addition to the index number.

I want to do what a for loop does without the check if the index number is >= 0 and without reducing the index number by one.

These two operations are not much usually, but in my case they take roughly 1/3 of the number of operations. So I wonder if I can do it this way:

switch (Parlist.Length)
{
    case 1024:
        ParList[1023].update;
        goto case 1023;
    case 1023:
        ParList[1022].update;
        goto case 1022;
    //and so on until
    case 1:
        ParList[0].update;
        break;
}

While it looks horrible, and I am aware this is not how it should be done, first tests make it look like I actually can rise performance quite much here. I would like to put this away into a class and access it in a more general manner like the foreach syntax is translated into a for loop. I would it to end up like this way:

eachcase (particle p in ParList)
{
    //instructions using p
}

which is translated into this:

switch (Parlist.Length)
{
    case 1024:
        //reference to instructions using Parlist[1023]
        goto case 1023;
    //and so on until
    case 1:
        //reference to instructions using Parlist[0]
        break;
}

How do I build such custom structures? Is this possible in C#?

If I am able to make this working, I also would like to implement a custom break condition like this:

eachcase (particle p in ParList, p.x == 0 && p.z == 0)
{
    //instructions using p
}

which is translated into this:

switch (Parlist.Length)
{
    case 1024:
        if (/*break condition*/) break;
        //reference to instructions using Parlist[1023]
        goto case 1023;
    //and so on until
    case 1:
        if (/*break condition*/) break;
        //reference to instructions using Parlist[0]
        break;
}

I read about Lambda expressions which can help me here but I am not sure how to connect it to a usual object array.

Looking into how foreach works, I found it is just a basic for loop, with doing a comparison and an addition to the index number.

That's how it works for arrays because that's the most efficient way of navigating arrays, but that's not how it works in general. It is optimized by the compiler to use the index for arrays. Other collection types will have a GetEnumerator() method that will return some object that has methods to navigate through the collection. How it does that is completely defined by the enumerator's implementation. For List that enumeration is just incrementing the index and using the indexer (very similar to the array, but with the small overhead of the enumerator object).

I don't see how your "switch" statement is an improvement. All you're doing is hard-coding a loop into N statements. I find it hard to believe that the bounds checking is a significant amount of your program time. You have an enormous amount of duplicate code, the limit is finite (foreach loops could loop forever if the underlying collection is infinite), and it's much harder (IMHO) to understand the intent.

Now I wonder how many particles my system can handle

That's easy. Set it to the maximum size of the underlying collection type (~2 billion elements if Particle is a reference type, possibly less if it's a value type). If your system can handle that, then you're good to go. If not, then reduce the size until you find your limit.

and if I can optimize it to raise that number.

Well before you can optimize you have to figure out where the inefficiencies are. Find the operations that take up the most program time and work on those first.

I would not assume that the foreach has an efficiency problem. If you measure the performance of your program and determine that the foreach itself (the loop, not what each iteration is doing), then start looking for alternatives.

If your process is CPU bound (meaning that it pegs a single logical processor at 100% then you might benefit from parallelization. You might try things like PLinq or TPL and see if the benefit of parallelization outweighs the overhead it creates.

Playing with the Switch and Foreach Statements, follows a case, there must be a break or similar jump statement). And it added the 'goto case' statement that can be used for fall-through effects. Still, this code is very different from the foreach alternative. Again, it gives the same results, and this time the ListCities() method is called only once, but yields 575 items, while with foreach, it yielded only 47 items. The difference comes from the fact that ToList() causes all data to be loaded from the database.

switch - Manual, The switch statement is similar to a series of IF statements on the same expression. The alternative syntax for control structures is supported with switches. foreach($a as $b) { a database for a mod I made for a Simple Machines forums, but this example uses arrays for links if you wanted to add your own custom links: In this article, we will pick up some switch examples, and we will try to provide several alternatives that eliminate or hide the switch statements. Learn JAVA and Start your Free Trial today! 1. Implementing the Strategy Pattern via Java Enum Application Name: SwitchToStrategyEnum

Try Select(), it is more efficient than loops https://www.reddit.com/r/csharp/comments/4xb0d9/why_is_linqs_select_better_than_foreach/

ParList = ParList.Select(s => s.update).ToArray();

C# switch Statement (With Examples), In this article, we will learn about switch statement in C# and how to use them with examples. The default statement at the end of switch is similar to the else block in if else statement. C# foreach Loop The information does not usually directly identify you, but it can give you a more personalized web experience. Prerequisite: Decision making in Java For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop.

The JavaScript Switch Statement (With Examples), The comparison value will match either a statement value or trigger a default code block. Switch statement is used as an alternate to multiple if .. Updated for Xcode 12.0. You will commonly find that you want to loop over a sequence to create views, and in SwiftUI that’s done using ForEach.. Important: It’s easy to look at ForEach and think it’s the same as the forEach() method on Swift’s sequences, but this is not the case as you’ll see.

How to create views in a loop using ForEach, ForEach in SwiftUI is a view struct in its own right, which means you can return If you have custom types in your array, you should use id: with whatever As an alternative, if you make Result conform to Identifiable protocol you can that uniquely identifies each object, which in our case we already have. The switch case is a decision-making statement that enables switching on a single variable where that variable may have one or multiple possible values. The switch statement is available in many programming languages including Java, PHP, JavaScript etc. However, Python has no switch case statement.

Statements - Simple Issue Language™, Custom Field types the standard for or simply for form; the foreach form Similar to C, C++ or Java of the for statement can be expressed as follows: ? The switch statement offers support for executing different operations� ForEach and Where are two frequently used concepts that have been available in PowerShell since version 1 came out in 2006. ForEach has been available as both a statement and a cmdlet (ForEach-Object), allowing you to iterate through a collection of objects and take some action once for each object in that collection.

Comments
  • Why not just use "break;" within the for-loop, or am i missing something? How exactly do you explain the performance going up?
  • Read here : stackoverflow.com/questions/365615/…
  • @matteocracco I am not sure how this is related to me, I already know foreach is based on for. I try to create something better here by using switch case.
  • @blackforest-tom A for loop uses an int as the index number, and after every step it adds 1 to it and checks if it is still not a negative number. These two operations are not needed in my switch case idea.
  • Btw, foreach uses iterators (c# yield) on your List<>, whereas you probably want a real array and a for-loop with indices. Did you try out that approach in terms of performance?
  • That article is comparing Linq to the ForEach() method on List<T>, not the foreach statement. Select does essenatially the same thing that foreach does, so there should not be any significant efficiency - in fact it may be less efficient since you have the overhead of an iterator object.
  • Both ForEach() and foreach is essentially a for loop, the Select() itself is fast because of the deferred execution.
  • Neither of those is "essentially a for loop" in all cases, but that's a different argument. Select is "essentially a foreach loop" also since it creates an enumerator and enumerates the underlying collection (deference is not material here since you're calling ToArray() immediately after it). Plus yours has the disadvantage of copying the results to a new array, which could significantly affect performance if the collection is large.
  • As D Stanley mentioned, deferred execution will not provide any performance gain in this scenario. You can read more about deferred execution here: blogs.msdn.microsoft.com/charlie/2007/12/10/…