释放分配给C中哈希表的内存的最快方法

时间:2022-07-25 18:52:33

Im looking for a faster method of freeing up memory allocated to a hash table in my code. What I've written below works but I want to know if there is another method that would accomplish the task faster.

我正在寻找一种更快的方法来释放我的代码中分配给哈希表的内存。我在下面写的内容有效但我想知道是否有另一种方法可以更快地完成任务。

bool unload(void)
{
    if (load)
    {
        node* temp;
        node* crawler;

        for(int n = 0; n < TABLESIZE; n++)
        {   
            if (hashtable[n] != NULL)
            {    
                // If only 1 node free it
                crawler = hashtable[n];
                while (crawler != NULL)
                {
                    temp = crawler->next;
                    free(crawler);
                    crawler = temp;

                }
                // free last node in list
                temp = crawler;
                free(temp);
            }        
        }
        return true;
    }
    return false;    
}

1 个解决方案

#1


2  

        while (crawler != NULL)
        {
        …
        }
        // free last node in list
        temp = crawler;
        free(temp);

When the loop exits, crawler is equal to NULL. Therefore, while it is perfectly acceptable to pass it to free(), you can save some time by not doing so.

当循环退出时,爬虫等于NULL。因此,尽管将它传递给free()是完全可以接受的,但是你可以通过不这样做来节省一些时间。

#1


2  

        while (crawler != NULL)
        {
        …
        }
        // free last node in list
        temp = crawler;
        free(temp);

When the loop exits, crawler is equal to NULL. Therefore, while it is perfectly acceptable to pass it to free(), you can save some time by not doing so.

当循环退出时,爬虫等于NULL。因此,尽管将它传递给free()是完全可以接受的,但是你可以通过不这样做来节省一些时间。