Advertisement
Guest User

Untitled

a guest
Apr 14th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Npgsql;
  7. using System.Linq.Expressions;
  8. using System.Reflection;
  9. namespace LambdaTest
  10. {
  11. using CacheFuncType = System.Action<NpgsqlBinaryImporter, object>;
  12. static class Class1
  13. {
  14. static Dictionary<Type, CacheFuncType> FuncCache = new Dictionary<Type, CacheFuncType>();
  15. static Dictionary<Type, object> CreateValuemap(long idx)
  16. {
  17. return new Dictionary<Type, object>()
  18. {
  19. { typeof(long),idx }
  20. ,
  21. { typeof(string),"mogemoge"+idx.ToString() }
  22. ,
  23. { typeof(DateTimeOffset),DateTimeOffset.Now }
  24. };
  25. }
  26. static Expression<CacheFuncType> CreateWriteLambda(Type t)
  27. {
  28. var source = Expression.Parameter(typeof(object), "source");
  29. var objparam = Expression.Parameter(typeof(NpgsqlBinaryImporter), "writer");
  30. var emethod = Expression.Call(objparam, "Write", new Type[] { t }, Expression.Convert(source, t));
  31. return Expression.Lambda<CacheFuncType>(emethod, objparam, source);
  32. }
  33. static void BulkInsertTest(NpgsqlConnection con)
  34. {
  35. var sw = new System.Diagnostics.Stopwatch();
  36. sw.Start();
  37. using (var writer = con.BeginBinaryImport("copy test2(a,b,c) from stdin(format binary)"))
  38. {
  39. for (int i = 0; i < 1000000; i++)
  40. {
  41. writer.StartRow();
  42. //writer.Write((long)i);
  43. //writer.Write(string.Format("mogemoge{0}", i));
  44. //writer.Write(DateTimeOffset.Now);
  45. var valueMap = CreateValuemap(i);
  46. foreach (var kv in valueMap)
  47. {
  48. if (!FuncCache.ContainsKey(kv.Key))
  49. {
  50. var lambda = CreateWriteLambda(kv.Key);
  51. FuncCache[kv.Key] = lambda.Compile();
  52. }
  53. FuncCache[kv.Key].Invoke(writer, kv.Value);
  54. }
  55. }
  56. }
  57. Console.WriteLine($"{sw.Elapsed}");
  58. }
  59. public static void Test()
  60. {
  61. var cb = new NpgsqlConnectionStringBuilder();
  62. cb.Host = "localhost";
  63. cb.Port = 5432;
  64. cb.Database = "test";
  65. cb.Username = "testuser";
  66. cb.Password = "hogehoge";
  67. cb.CommandTimeout = 0;
  68.  
  69. using (var con = new NpgsqlConnection(cb))
  70. {
  71. con.Open();
  72. using (var cmd = con.CreateCommand())
  73. {
  74. cmd.CommandText = "truncate table test2";
  75. cmd.ExecuteNonQuery();
  76. }
  77. BulkInsertTest(con);
  78. }
  79. }
  80. }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement