Loop memory and processing optimization

Asked

Viewed 219 times

1

The code is simple and is working perfectly, but wanted tips on how to optimize it, what would be the best methods to use to allocate less memory, best practices, etc.

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> numeros = new List<int>();
        List<int> pares = new List<int>();
        List<int> impares = new List<int>();

        Random random = new Random();

        for(int i = 0; i < 20; i++)
        {
            int n = random.Next(1, 99);
            numeros.Add(n);
        }

        foreach (int item in numeros)
        {
            if (item % 2 == 0)
                pares.Add(item);
            else
                impares.Add(item);
        }

        Console.WriteLine("Todos os números:");

        int index = 0;

        foreach (int item in numeros)
        {
            if (index == numeros.Count - 1)
                Console.Write(item + "." + "\n");
            else
                Console.Write(item + ", ");

            index++;
        }

        index = 0;

        Console.WriteLine("\n" + "Números pares:");

        foreach (int item in pares)
        {
            if (index == pares.Count - 1)
                Console.Write(item + "." + "\n");
            else
                Console.Write(item + ", ");

            index++;
        }

        Console.WriteLine("\n" + "Números ímpares:");

        index = 0;

        foreach (int item in impares)
        {
            if (index == impares.Count - 1)
                Console.Write(item + "." + "\n");
            else
                Console.Write(item + ", ");

            index++;
        }
    }
}
  • 1

    What would be the requirement ? looks like one of those college exercises, and there’s a teacher who asks for each process to be done in a different loop, rs, would have to see the requirements to know what can be changed

  • That’s right. There’s no rule, just keep the result the way it is. I want to learn a little about optimization to apply in more complex codes in the future.

2 answers

3

Optimization can be a lot. It can be by performance, memory consumption, it can be by code or even other things to be defined. Optimization has to test. And what is worth today may not be worth tomorrow.

Optimizing this code should not bring much advantage. One of the few performance improvements is to find out if you’re paired with a bit operator that’s usually faster than the rest operator, but the compiler could do an optimization and not change anything. Some things may still be done, but it depends on testing to prove that they are optimizations.

The rest I can just slow down and modernize the code. Of course, I could delete one or two of the lists, which could occupy half the memory, but I see no advantage. Has reduction that probably creates optimization, for example removing a branching (comparison if or ternary) inside a loop as I did in the prints.

As there are no requirements it becomes difficult to know what to do. In fact maybe I could cut something else.

As the printing of the lists are identical could play on a function to eliminate code duplicity, but it may not be the intention.

There are other small details that could be different, but it depends on taste.

using System;
using static System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main(string[] args) {
        var numeros = new List<int>();
        var pares = new List<int>();
        var impares = new List<int>();
        var random = new Random();
        for (int i = 0; i < 20; i++) numeros.Add(random.Next(1, 99));
        foreach (int item in numeros) {
            if ((item & 1) == 0) {
                pares.Add(item);
            } else {
                impares.Add(item);
            }
        }
        WriteLine("Todos os números:");
        for (int i = 0; i < numeros.Count - 1; i++) Write(numeros[i] + ", ");
        WriteLine(numeros[numeros.Count - 1] + ".");
        WriteLine("\nNúmeros pares:");
        for (int i = 0; i < pares.Count - 1; i++) Write(pares[i] + ", ");
        WriteLine(pares[pares.Count - 1] + ".");
        WriteLine("\nNúmeros ímpares:");
        for (int i = 0; i < impares.Count - 1; i++) Write(impares[i] + ", ");
        WriteLine(impares[impares.Count - 1] + ".");
    }
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

  • Thanks for your help. Of course, for this code you don’t need to worry about memory and performance, but I need to learn now for future more complex codes. Besides, also, learning the reductions and abbreviations. I did not understand well the line that determines the pairs if ((item & 1) == 0), could explain?

  • See https://answall.com/q/190579/101 and https://answall.com/q/52949/101. It tests only one bit in a very low cost operation. Only the least significant bit already identifies whether it is even or odd, there is no need to make a complex calculation as is the division to catch the rest.

2


Only a few changes, it is still possible to do more, but I see no need to complicate. rs

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        List<int> numeros = new List<int>();
        List<int> pares = new List<int>();
        List<int> impares = new List<int>();

        Random random = new Random();

        for(int i = 0; i < 20; i++)
        {
            int n = random.Next(1, 99);
            numeros.Add(n);
            if (n % 2 == 0)
                pares.Add(n);
            else
                impares.Add(n);

        }

        Console.WriteLine("Todos os números:");


        for (int i =0; i < numeros.Count; i++)
           Console.Write( numeros[i].ToString() + (i == numeros.Count-1 ? ".\r\n" : ", " ));


        Console.WriteLine("\nNúmeros pares:");

        for (int i =0; i < pares.Count; i++)
           Console.Write( pares[i].ToString() + (i == pares.Count-1 ? ".\r\n" : ", " ));


        Console.WriteLine("\nNúmeros ímpares:");

        for (int i =0; i < impares.Count; i++)
           Console.Write( impares[i].ToString() + (i == impares.Count-1 ? ".\r\n" : ", " ));

    }
}

I put in the .NET Fiddle

  • Thanks for your help. I could explain this line? (i == numeros.Count-1 ? ".\r\n" : ", " )

  • Never mind, I figured out what it’s all about :)

  • rsrs, ternary operator, =]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.