How expensive is it to dereference a pointer?

后端 未结 6 1547
攒了一身酷
攒了一身酷 2020-12-12 15:07

How expensive is it to perform the dereference operation on a pointer?

I can imagine that the memory transfer is somehow proportional to the object size, but I want

6条回答
  •  忘掉有多难
    2020-12-12 15:52

    Dereferencing(multiple) cost CPU cycles.

    Instead of writing:

    string name = first->next->next->next->name;
    int age = first->next->next->next->age;
    
    this is O(n)
    


    Write it as:

    node* billy_block = first->next->next->next;
    
    string name = billy_block->name;
    int age = billy_block->age;
    
    this is O(1)
    

    So your code will not "ask" each and every block just to get to the fourth block.

    Multiple dereferencing is like having a neighborhood who only knows a neighbor next to them.

    Imagine if you ask a person from the first block where does your friend Billy resides, he will tell you he doesn't know your friend, he'll tell you he only know the neighbor next to them, then he'll just tell you to ask his neighbor, then you'll ask his neighbor, he'll answer the same thing as the first block did, you keep asking until you arrive at your friend's block. Not very efficient

提交回复
热议问题