UTF8BytesCache.cs 761 B

12345678910111213141516171819202122232425262728293031
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Pomelo.DotNetClient
  6. {
  7. internal class UTF8BytesCache
  8. {
  9. public static readonly UTF8BytesCache Instance = new UTF8BytesCache();
  10. private readonly Dictionary<string, byte[]> cache = new Dictionary<string, byte[]>();
  11. private UTF8BytesCache(){}
  12. public byte[] GetBytes(string str)
  13. {
  14. lock(cache)
  15. {
  16. byte[] ret;
  17. if (cache.TryGetValue(str, out ret))
  18. {
  19. return ret;
  20. }
  21. ret = Encoding.UTF8.GetBytes(str);
  22. cache.Add(str, ret);
  23. return ret;
  24. }
  25. }
  26. }
  27. }