Skip to content

Instantly share code, notes, and snippets.

@filipnavara
Created April 18, 2019 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filipnavara/31791b216078706e0b465f7a103ff01f to your computer and use it in GitHub Desktop.
Save filipnavara/31791b216078706e0b465f7a103ff01f to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <search.h>
typedef struct { int32_t key; void* UCollator; } TCollatorMap;
static int TreeComparer(const void* left, const void* right)
{
const TCollatorMap* leftMap = left;
const TCollatorMap* rightMap = right;
if (leftMap->key < rightMap->key) return -1;
if (leftMap->key > rightMap->key) return 1;
return 0;
}
void *collatorsPerOptionRoot = NULL;
int created = 0;
static void *GetCollator(int32_t options)
{
void *pCollator;
TCollatorMap* map = (TCollatorMap*)malloc(sizeof(TCollatorMap));
map->key = options;
void* entry = tfind(map, &collatorsPerOptionRoot, TreeComparer);
if (entry == NULL)
{
pCollator = malloc(1000);
created++;
map->UCollator = pCollator;
tsearch(map, &collatorsPerOptionRoot, TreeComparer);
}
else
{
free(map);
pCollator = (*(TCollatorMap**)entry)->UCollator;
}
return pCollator;
}
int main()
{
for (int j = 0; j < 1000000; j++)
for (int i = 0; i < 12; i++)
{
GetCollator(i);
GetCollator(i);
}
printf("created: %d\n", created);
return 0;
}
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <search.h>
typedef struct { int32_t key; void* UCollator; } TCollatorMap;
static int TreeComparer(const void* left, const void* right)
{
const TCollatorMap* leftMap = left;
const TCollatorMap* rightMap = right;
if (leftMap->key < rightMap->key) return -1;
if (leftMap->key > rightMap->key) return 1;
return 0;
}
void *collatorsPerOptionRoot = NULL;
int created = 0;
static void *GetCollator(int32_t options)
{
void *pCollator;
TCollatorMap* map = (TCollatorMap*)malloc(sizeof(TCollatorMap));
map->key = options;
void* entry = tsearch(map, &collatorsPerOptionRoot, TreeComparer);
//void* entry = tfind(map, &collatorsPerOptionRoot, TreeComparer);
if ((*(TCollatorMap**)entry) == map)
//if (entry == NULL)
{
pCollator = malloc(1000);
created++;
map->UCollator = pCollator;
//tsearch(map, &collatorsPerOptionRoot, TreeComparer);
}
else
{
free(map);
pCollator = (*(TCollatorMap**)entry)->UCollator;
}
return pCollator;
}
int main()
{
for (int j = 0; j < 1000000; j++)
for (int i = 0; i < 12; i++)
{
GetCollator(i);
GetCollator(i);
}
printf("created: %d\n", created);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment