Thread: HashTable KeySize

HashTable KeySize

From
Natarajan R
Date:
typedef struct HashTableKey
{
  Oid dbId; // 4 bytes
  int64 productid; // 8 bytes
}HashTableKey; (total size - 12 bytes)

typedef struct HashTableEntry
{
  HashTableKey key;
  ProductInfo *pdt;
}HashTableEntry;

HASHCTL hashInfo;
hashInfo.keysize = sizeof(HashTableKey);
hashInfo.entrysize = sizeof(HashTableEntry);
SampleHashTable = ShmemInitHash("productid vs product struct HashTable", size, size, &hashInfo, HASH_ELEM | HASH_SHARED_MEM | HASH_BLOBS);

while printing keysize: elog(LOG,"Keysize = %d",sizeof(HashTableKey));

I am getting Keysize = 16, How? what should i need to do inorder to have keysize = 12

Re: HashTable KeySize

From
Tomas Vondra
Date:
On Fri, Oct 04, 2019 at 05:06:47PM +0530, Natarajan R wrote:
>typedef struct HashTableKey
>{
>  Oid dbId; // 4 bytes
>  int64 productid; // 8 bytes
>}HashTableKey; (total size - 12 bytes)
>
>typedef struct HashTableEntry
>{
>  HashTableKey key;
>  ProductInfo *pdt;
>}HashTableEntry;
>
>HASHCTL hashInfo;
>hashInfo.keysize = sizeof(HashTableKey);
>hashInfo.entrysize = sizeof(HashTableEntry);
>SampleHashTable = ShmemInitHash("productid vs product struct HashTable",
>size, size, &hashInfo, HASH_ELEM | HASH_SHARED_MEM | HASH_BLOBS);
>
>while printing keysize: elog(LOG,"Keysize = %d",sizeof(HashTableKey));
>
>I am getting Keysize = 16, How? what should i need to do inorder to have
>keysize = 12

That's likely due to alignment. The second field is a 64-bit value will
be aligned at 8-byte boundary, so in memory the struct will look like
this:

  dbId -- 4 bytes
  padding -- 4 bytes
  productId -- 8 bytes

See

  https://en.wikipedia.org/wiki/Data_structure_alignment

and there's also a tool to show the memory layout:

  https://linux.die.net/man/1/pahole


regards

-- 
Tomas Vondra                  http://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services