简体   繁体   中英

C# BigInteger and int How to save memory?

I am testing a matrix if it has a prime number in every line.

The MR means that it should use the Miller Rabin algorithm. If its false it simply tries the divisors up to sqrt(n). Vansor is true if it has found a prime in every checked row, vanoszlop is true if it has found a prime in the actually checked row.

My question is: Is it possible to save the memory by not creating both the int and BigInteger values only if the tryParse is true? I mean something like

if (int.tryParse(akt, out new int szam))

Is something like this possible? (and how much memory does a BigInteger take when its not signed?)

    akt = Console.ReadLine();
    int szam; BigInteger szambig;

    if (int.TryParse(akt, out szam))
    {
       if (MR)  {
          if (MilRab(szam))
          { vansor = true; vanoszlop = true; } }

          else if (Prim(szam))
          { vansor = true; vanoszlop = true; }
    }
    else if (BigInteger.TryParse(akt, out szambig))
    {
       if (MR) {
          if (MilRab(szam))
          { vansor = true; vanoszlop = true; } }

       else if (Prim(szam))
       { vansor = true; vanoszlop = true; }
    }

I'm not 100% sure on how .Net IL optimizes memory, but in general local "value" type (as opposed to "reference" types) are kept on the stack. IE, you would only save the ~4 bytes that an integer takes up by not instantiating it, and only for the lifetime of that one call. Once you exit the function, the stack is cleared.

Structures are "value" types, and are also placed on the stack. They reserve memory for all other value types & reference pointers as needed. The size of a BigInteger is the same whether or not "Signed" is true or false.

I suppose my real question is: why the memory obsession? With the code example you have, you'll take a few dozen bytes of memory that will all be freed up when the method exits.

If you managed to do it, at best you would save 16 bytes that BigInteger takes up on 64-bit mode (I guess).

I'm pretty sure that's not worth worrying about. In situations where those 16 bytes are important:

  1. you probably shouldn't be using .Net
  2. you most likely don't have .Net available anyway

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM