<2026年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

  • 随笔 - 1
  • 文章 - 2
  • 评论 - 0
  • 引用 - 0

常用链接

留言簿(1)

随笔档案

文章分类

文章档案

搜索

  •  

最新评论

Dynamic Array
Some Tips

1. Be sure to destroy every dynamic array that you created, or you will have a memory leak.

2. When you use free, always reset your pointers to 0 after freeing, even if you don't plan on using them again.

3. Never writer over a pointer to an array that you have not destroyed unless you've stored the address of the array somewhere else first.You will end up with memory leak.

  // a example
  int  *pArray = 0;
  int  *temp = 0;

  pArray = (int *)malloc(10 * sizeof(int));
 
  temp = pArray;      // store the address of the array
  pArray = (int *)realloc(pArray, 20 * sizeof(int));
 
  // memory allocation fail
  if (pArray == 0)
  {
      pArray = temp;
   }

4. Always check to see  if your memory allocations have not  failed.

5. When deleting an array, always use the bracket notation, or delete will only destroy the first cell and this will lead to memory leak.

Cache Issues

Arrays are great for being able to access every item in the array randomly, in theory. In reality, arrays aren't actually randomly accessible. This has to do with the way computers actually work. A computer is a complex machine with many lays of memory. The lowest of these lays is called registers, and all processors have a larger memory area almost as fast as the registers called the level 1 cache(L1 cache). There might be other levels of cache as well. So whenever datas needs to be accessed, the processor needs to search for it in one of the memory levels. 

So that's one thing you have to pay attention to when dealing with arrays. Looping through them in a single loop is nice and fast because you use as much of the array as possible at one time. However, an algorithm that randomly jumps to different cells that are far away from each other will be slow because you're causing the processor to move around a great deal of memory. Profiling programs have shown that the processor spends most of its time moving memory around, which is a major optimization concern.

posted on 2009-02-28 18:46 易小寒 阅读(326) 评论(0)  编辑 收藏 引用 所属分类: Data Structure


只有注册用户登录后才能发表评论。
相关文章:
网站导航:   博客园   博客园最新博文   博问   管理