C # fixed-size cache

Source: Internet
Author: User

Sometimes you need to save the latest N records for the time needed to call, C # There is no pointer, how to do it? We use arrays and byte bytes to complete a class:

     Public classBuffer<t>    {        Privatet[] _ts; Private byte_index =0; Private int_capcity;  PublicBuffer (intcapcity) {            //sets the size of the array to 2 of the n-th square             while(Capcity & Capcity-1) !=0) capcity++; _ts=NewT[capcity]; _capcity=capcity; }         Public voidWrite (T t) {_ts[_index% _capcity] =T; _index++; }         PublicIenumerable<t>Read () {byteindex =_index;  for(inti =0; I < _ts. Count (); i++) {Index--; yield return_ts[index%_capcity]; }        }    }

Explain:

1.byte _index=0;

_index--; =0xff

_index++;//=0

The use of this feature of Byte, write the time + +, read time--without regard to the boundary, is not more convenient.

2. Why is the size of the array automatically adjusted to the n-th square of 2?

That is because only 2 of the nth Time, (0xFF _capcity) ==_capcity-1, to achieve the traversal of the array.

To test, call the following code:

        Static voidMain (string[] args) {Buffer<int> buffer =Newbuffer<int> (Ten); varTaskwrite = Task.Factory.StartNew (() =            {                 for(inti =0; I < -; i++) {buffer.                    Write (i); Console.WriteLine ($"Write:i={i}"); Task.delay ( -).                Wait ();            }            }); varTaskread = Task.Factory.StartNew (() =            {                 for(inti =0; I <7; i++) {Console.WriteLine ("Read:"+string. Join (",", buffer.                    Read ())); Task.delay ( +).                Wait ();            }            });        Task.waitall (Taskwrite, Taskread); }    }

Results:

Suitable for:

1. Small cache, <=255

Of course you can >255, as long as the type of _index to Uint16,uint32 or UInt64, the size is 0xffff,0xffffffff and 0xFFFFFFFFFFFFFFFF, but so much useful? Is it called cache?

2. Single-thread read single-threaded write operation

C # fixed-size cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.