C#BigInteger和int如何节省内存? [英] C# BigInteger and int How to save memory?

查看:205
本文介绍了C#BigInteger和int如何节省内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在测试矩阵是否在每行中都有素数.

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

MR表示应使用Miller Rabin算法.如果其为假,则仅尝试除数直到sqrt(n).如果Vansor在每个选中的行中都找到了素数,则为true;如果在实际选中的行中找到了素数,则vanoszlop为true.

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.

我的问题是:仅当tryParse为true时,才可以通过不同时创建int和BigInteger值来节省内存吗?我的意思是

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))

像这样可能吗? (以及BigInteger未签名时需要占用多少内存?)

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

推荐答案

我不确定.Net IL如何优化内存,但是一般而言,本地值"类型(与引用"类型相对)是100%的.放在堆栈上. IE,您只会通过不实例化一个整数来保存它占用的〜4个字节,并且仅在该调用的整个生命周期内保存.退出该功能后,将清除堆栈.

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.

结构是值"类型,也放置在堆栈中.它们为所有其他值类型&保留内存.根据需要引用指针.无论签名"为真还是假,BigInteger的大小都是相同的.

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.

这篇关于C#BigInteger和int如何节省内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆