C# BigInteger and int How to save memory?

点点圈 提交于 2020-01-06 14:16:17

问题


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; }
    }

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/8083128/c-sharp-biginteger-and-int-how-to-save-memory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!