bench.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var ProtoBuf = require("../index.js");
  2. var sample = {
  3. id: 1,
  4. name: "John123",
  5. password: "helloworld"
  6. };
  7. console.log("Sample: `"+JSON.stringify(sample, null, 4));
  8. console.log("\n");
  9. var proto = " message Sample {" +
  10. "required uint32 id = 1;" +
  11. "required string name = 2;" +
  12. "required string password = 3;" +
  13. "}";
  14. var builder = ProtoBuf.loadProto(proto, "bench.proto"),
  15. Sample = builder.build("Sample");
  16. // Compare size
  17. console.log("Encoding size");
  18. console.log("-------------");
  19. var jsonData = new Buffer(JSON.stringify(sample), "utf8"),
  20. protoData = new Sample(sample).toBuffer();
  21. console.log("* Encoded sample size as JSON: "+jsonData.length+" bytes");
  22. console.log("* Encoded sample size as protocol buffer: "+protoData.length+" bytes");
  23. console.log("");
  24. // Compare encoding speed
  25. console.log("Encoding speed");
  26. console.log("--------------");
  27. (function() {
  28. // Assuming that a receive buffer is used
  29. var buf = ProtoBuf.ByteBuffer.allocate(64);
  30. var protoSample = new Sample(sample),
  31. n = 100000, k = (n/1000)+'k';
  32. console.time("* ProtoBuf encode "+k);
  33. for (var i=0; i<n; ++i)
  34. protoSample.encode(buf, true),
  35. buf.flip();
  36. console.timeEnd("* ProtoBuf encode "+k);
  37. console.time("* ProtoBuf decode "+k);
  38. for (var i=0; i<n; ++i)
  39. Sample.decode(buf),
  40. buf.flip();
  41. console.timeEnd("* ProtoBuf decode "+k);
  42. })();