Creating C # Cache with Byte [] and Eviction Policy

I want to create an eviction policy cache in C #. My key is a byte array (fixed at 32 bytes), and the value is an instance of a particular class.

I am discussing the best way to do this. I think MemoryCache is the way to go, but it uses string for the key. I could turn this into a hexadecimal string, but it does impose some overhead. Why is the key not an arbitrary object, for example, in a dictionary?

It is trivial to write a comparative array of bytes and there is a suitable Dictionary constructor for delivering IEqualityComparer , but this approach does not give me a free eviction strategy.

Are there any other options that I skip?

+4
source share
2 answers

MemoryCache is actually quite complicated under the hood (grab a copy of Reflector and see if you haven't already). There are several things that are not trivial to replicate; the main one is the approximation of the amount of memory used by cached objects.

In terms of performance, you will deal with significantly more significant impacts than massaging the key. Performance is acceptable, but key management is an insignificant part of the process.

You can see this difference by doing 100K + add operations in Dictionary compared to MemoryCache .

Here is a small hexadecimal algorithm that you can use on your byte keys, which I configured as quickly as possible. BCL also contains basic functionality 16 (which I did not know when I wrote this code, and I saved it because it is simpler / faster).

As noted in the comments, converting byte[] to hex is probably not even required to satisfy stated requirements if the key is not to be used elsewhere.

 public unsafe sealed class Hex { private static readonly char[] _hexRange = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /// <summary> /// Converts a byte array into a string of base-16 values. /// </summary> /// <param name="value">Value to convert.</param> /// <returns>Base-16 encoded string.</returns> public static string ToHexString( byte[] value ) { char* buffer = stackalloc char[( value.Length * 2 ) + 1]; // +1 for null terminator char* start = buffer; for( int i = 0; i < value.Length; i++ ) { *buffer++ = _hexRange[value[i] / 16]; *buffer++ = _hexRange[value[i] % 16]; } return new string( start ); } } 
+3
source

Well, one solution would be to look for a library on the Internet. Like an LRU list.

On the other hand, MemoryCache is well tested and well designed. Most likely, it will be pretty fast. If the performance overhead when calculating string keys is acceptable, I would just go with this solution. I assume that calculating a key is much less overhead than doing a cache operation, but this is an assumption (you need to measure).

+1
source

Source: https://habr.com/ru/post/1413622/


All Articles