Приложения.NET являются естественно интенсивно использующими память?

Одна стандартная проблема: процесс мог ожидать Вас для чтения его вывода. Создайте отдельный поток для чтения из его стандартного вывода, в то время как Вы ожидаете его для выхода. Это - что-то вроде боли, но это может быть проблемой.

5
задан George Stocker 8 October 2009 в 21:55
поделиться

8 ответов

Using Task Manager to look at your memory usage is likely to be horrendously inaccurate.

Instead, grab a proper memory profiling tool (dotTrace is very good, and has a 10 day trial) and take the time to see your actual memory consumption.

The sorts of things I've seen in my own code include

  • Underestimating how much memory I'm actually using (not counting separate objects properly, not allowing for lists to have "spare" capacity)
  • Keeping references to transient objects that I don't need
  • Not allowing for transient objects created during operation that haven't yet been garbage collected
  • Not allowing for unallocated memory - memory that has been claimed from the OS (and therefore shows as a part of the process in Task Manager) but which has't been allocated to any one object yet
  • Not allowing for thread stacks (each thread gets a stack of its own; .NET applications are always multi-threaded as the framework may create several threads of its own).
7
ответ дан 18 December 2019 в 07:10
поделиться

Как вы определили, сколько памяти было использовано? Известно, что приложения .NET охотно резервируют больше памяти, чем им нужно, пока имеется много доступной памяти, и возвращают память системе, если она начинает не хватать памяти.

Думаю, вы можете найти несколько указателей в этой статье MSDN .

12
ответ дан 18 December 2019 в 07:10
поделиться

В те дни, когда у нас есть несколько ГБ ОЗУ на машине, идея о том, что приложение, ориентированное на пользователя, такое как вы обычно создаете на C #, должно использовать только несколько 100 КБ ОЗУ, является обратной. Любая неиспользуемая оперативная память в вашей системе тратится впустую.

Имея это в виду, C # выделяет память, используя совершенно другую стратегию, чем C ++, так что большие блоки выделяются и освобождаются реже.

Тем не менее, 40 кажется немного большим. Я привык к чему-то ближе к 10-14Мб для очень простых консольных приложений. Может быть, есть форма, занимающая память, или, может быть, я использую другую версию фреймворка (2.0).

5
ответ дан 18 December 2019 в 07:10
поделиться

The .Net runtime has a certain large overhead - we've found that even simple applications will tend to use much more memory that similar applications written in C++. Fortunately this overhead is quickly disipated in the noise as the size of the overall code increases. The second factor is that of garbage collection, the garbage collector runs "whenever", so by comparison to C++, memory allocations are not typically freed right away, but rather when it feels the requirement to do so.

2
ответ дан 18 December 2019 в 07:10
поделиться

I'd say that unless you have a very good reason to worry about RAM usage, don't. Like optimizations, you should only optimize where there is a customer/end-user need to do so. I don't believe users are so constrained by memory these days (unless you're talking about an embedded system) that they're going to notice or care much about a missing 38 MB.

2
ответ дан 18 December 2019 в 07:10
поделиться

Дело не всегда в языке, а обычно в том, как он используется.

Хороший код может эффективно использовать память на любом языке.

Неверный код будет неэффективно использовать память на всех языках

2
ответ дан 18 December 2019 в 07:10
поделиться

If you are using Task Manager to look at the memory it can be misleading. Working Set is the amount of virtual memory mapped to the process. Not necessarily how much your application is using - this is especially true in .NET's garbage-collected environment. As your program allocates memory the .NET CLR/GC will usually request more memory than it actually needs from the OS so that it can efficiently allocate that memory to managed objects in your program in the future.

A quick and dirty way (very dirty) to see if this is affecting you is to set Process.MaxWorkingSet property to 0. This is similar to using SetProcessWorkingSetSize in Win32 to try and trim the amount of pages mapped to the process. If you immediately see a drop in the memory usage then you know what is going on. However, as soon as you start allocating memory again via the GC/CLR it will go back up - and usually that is a good thing. Really you shouldn't worry about it and give the GC a chance to do it the right way.

To both optimize your program's memory usage and get a better idea of how memory allocation works in the CLR I suggest you start messing with dotTrace (my preference), Ants Profiler (who incidentally publishes a cool video on this topic here). CLRProfiler is interesting too, but it is a bit dated these days, but it is free.

0
ответ дан 18 December 2019 в 07:10
поделиться

Doing a quick calc you are probably allocating around 340K objects (subtracting the usual c12MB hit for single console apps on 32bit, yikes Steve!) and seeing [removing the reference to a typical scenario eating 8bytes per object + then some for other usual suspects] of runtime and System.Object waste for reference types by the bloated runtime tech copyright @ Sun.com..

Try and design for value types / structs if at all possible.. if you cannot, tough, tell your users not to run more than 10 .NET apps or their machine will feel slower than C64. If it makes you feel better, try WPF or Silverlight and feel c100MB penalty for a few buttons and flashy animations.

(downvote feel)

-8
ответ дан 18 December 2019 в 07:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: