简体   繁体   English

哪个在C分配/释放使用局部变量的内存方面更好?为什么?

[英]Which is better in C allocating/deallocating memory of using a local variable? and Why?

If I need to do string manipulation or manipulating any kind of arrays be it stantard types like int or a self defined data structure. 如果我需要进行字符串操作或操纵任何类型的数组,那么它是stantard类型,如int或自定义数据结构。 What is better local variable or dynamically allocating and de-allocating memory? 什么是更好的局部变量或动态分配和解除分配内存?

I know that if you are using a local variable you will not need to allocate/de-allocate of the memory and that might save us from memory leaks. 我知道如果你使用局部变量,你将不需要分配/取消分配内存,这可能会使我们免于内存泄漏。 But I want to know why people like using dynamically allocate memory. 但我想知道为什么人们喜欢使用动态分配内存。 Is it just a coding style or does it really have its benefits. 它只是一种编码风格还是真的有它的好处。 Also does it depends on system on which we are compiling or does it depend on the compiler? 它还取决于我们正在编译的系统还是依赖于编译器?

Even if the system have enough resources for memory and speed which technique is better suited to optimize the code? 即使系统有足够的内存和速度资源,哪种技术更适合优化代码?

Local, stack-allocated operations will pretty much always trump dynamic memory allocation in terms of speed. 本地,堆栈分配的操作几乎总是胜过动态内存分配的速度。 The reason being that, during dynamic memory allocation, your program needs to ask the operating system for help. 原因是,在动态内存分配期间,您的程序需要向操作系统寻求帮助。 This causes a context switch (which are very slow/expensive), and blocks until the operating system returns you a block of memory (which it may not even be able to). 这导致上下文切换(非常慢/昂贵),并阻塞直到操作系统返回一块内存(它甚至可能无法)。

Your program however, has its own stack already, and so it can manipulate that as necessary without interrupting the flow of execution (other than multi-tasking which is out of your control anyway). 但是,您的程序已经拥有自己的堆栈,因此它可以在不中断执行流程的情况下根据需要进行操作(除了无法控制的多任务处理)。

The benefits to dynamic memory allocation are that sometimes we do not know how much we need to allocate until runtime. 动态内存分配的好处是有时我们不知道在运行时需要分配多少。 Without dynamic allocation, we would need to allocate a static buffer upfront, and reserve enough memory for the worst-case scenario (which we may or may not have enough resources for). 如果没有动态分配,我们需要预先分配一个静态缓冲区,并为最坏情况(我们可能有或没有足够的资源)保留足够的内存。

The question you should ask in this matter is: do I know the memory size the program's going to need in runtime? 你应该在这个问题上提出的问题是:我是否知道程序在运行时需要的内存大小?

If you know you'll be needing for instance only 3 int variables, then you should go for local variables. 如果你知道你只需要3个int变量,那么你应该选择局部变量。 No memory leak, and your program won't run unless there's enough memory available. 没有内存泄漏,除非有足够的可用内存,否则程序将无法运行。

If you can't predict how much memory you'll need, let's say if you need to read a file into memory, you have no choice but to go for dynamic allocation. 如果你无法预测你需要多少内存,那么假设你需要将文件读入内存,你别无选择,只能进行动态分配。

There are good reason for having both as options. 有两个选项是有充分理由的。

Typically, you will use a heap allocation (eg malloc ) when: 通常,您将在以下情况下使用堆分配(例如malloc ):

  • you don't know the size of the allocation you will need until execution 你不知道在执行之前你需要的分配大小
  • when it consumes a good amount of the stack memory (or all) 当它消耗大量的堆栈内存(或全部)时
  • when the allocation needs to live beyond the current scope (eg is returned from a function) 当分配需要超出当前范围时(例如从函数返回)

Also does it depends on system on which we are compiling or does it depend on the compiler? 它还取决于我们正在编译的系统还是依赖于编译器?

It depends on both the compiler and the system you are targeting. 它取决于您要定位的编译器和系统。

Even if the system have enough resources for memory and speed which technique is better suited to optimize the code? 即使系统有足够的内存和速度资源,哪种技术更适合优化代码?

What's more important is how you need to use and access the memory and the hardware in most cases. 更重要的是,在大多数情况下,您需要如何使用和访问内存和硬件。 A local variable has more advantage for optimization. 局部变量具有更多优化优势。 However, the compiler may optimize away calls to malloc , in some cases. 但是,在某些情况下,编译器可能会优化对malloc调用。

Local, non-malloc, calls will generally allocate/deallocate faster as they require only stack work and not heap management - and they have the added benefit of limited scope. 本地,非malloc调用通常会更快地分配/解除分配,因为它们只需要堆栈工作而不需要堆管理 - 并且它们具有有限范围的额外好处。 But, they have limited scope and often you need your memory to last beyond a function. 但是,它们的范围有限,通常你需要你的记忆才能超越一个功能。

On some embedded systems with limited stack space, one will call malloc even on local vars just to get access to the larger heap, but in general, you want to limit your memory access to the scope it is intended - regardless of performance considerations. 在一些具有有限堆栈空间的嵌入式系统上,即使在本地变量上也会调用malloc只是为了访问更大的堆,但一般来说,您希望限制内存访问其预期的范围 - 无论性能如何考虑。

As a default position, unless you have a need for the allocation to outlive the scope in which it's created, or the allocation is significant, stack allocation is preferred. 作为默认位置,除非您需要分配比创建它的范围更长,或者分配很重要,否则首选堆栈分配。 In your case, you're asking about a local variable, which should presumably be free'd at the end of the enclosing scope. 在你的情况下,你问的是一个局部变量,它应该在封闭范围的末尾被释放。 One rule of thumb is that if the allocation is less than 1K , stack is appropriate, otherwise heap. 一条经验法则是,如果分配小于1K ,则堆栈是合适的,否则堆。 Microsoft's _malloca uses this threshold to switch between stack and heap allocation. 微软的_malloca使用此阈值在堆栈和堆分配之间切换。 Of course, much depends on what state you expect the stack to be in for your allocation. 当然,很大程度上取决于您期望堆栈进入分配的状态。 For example, a 1K stack allocation in a deeply recursive function may not be wise. 例如,深度递归函数中的1K堆栈分配可能不明智。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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