Does the foreach loop in C# guarantee an order of evaluation?

For arrays (note that System.Array implements IEnumerable), it will access elements in order. For other types (IEnumerable, or having GetEnumerator), it accesses elements in the order provided, through alternating MoveNext and Current calls. The standard states (ECMA-334 §13.9.5): “The order in which foreach traverses the elements of an array, is as follows: For single-dimensional arrays … Read more

How to insert a counter into a Stream .forEach()?

You can use an AtomicInteger as a mutable final counter. public void test() throws IOException { // Make sure the writer closes. try (FileWriter writer = new FileWriter(“OutFile.txt”) ) { // Use AtomicInteger as a mutable line count. final AtomicInteger count = new AtomicInteger(); // Make sure the stream closes. try (Stream<String> lines = Files.lines(Paths.get(“InFile.txt”))) … Read more

Don’t use StringBuilder or foreach in this hot code path

I made the code change and yes it made a huge difference in number of allocations (GetEnumerator()) calls vs not. Imagine this code is millions of times per second. The number of enumerators allocated is ridiculous and can be avoided. edit: We now invert control in order to avoid any allocations (writing to the writer … Read more

Memory allocation when using foreach loops in C#

Foreach can cause allocations, but at least in newer versions .NET and Mono, it doesn’t if you’re dealing with the concrete System.Collections.Generic types or arrays. Older versions of these compilers (such as the version of Mono used by Unity3D until 5.5) always generate allocations. The C# compiler uses duck typing to look for a GetEnumerator() … Read more

tech