analytics-node icon indicating copy to clipboard operation
analytics-node copied to clipboard

minimize number of calls to JSON.stringify

Open schmod opened this issue 2 years ago • 0 comments

Small performance tweak.

Instead of calling JSON.stringify() on the entire queue of messages every time we enqueue a message, analytics-node will now keep a running tally of the queue size, and only call JSON.stringify() once when the message is enqueued.

This should offer a minor performance-improvement for anybody enqueuing lots of messages.


As an aside, I'm also wondering if this bit of code is actually relevant any more:

    if (!message.messageId) {
      // We md5 the messaage to add more randomness. This is primarily meant
      // for use in the browser where the uuid package falls back to Math.random()
      // which is not a great source of randomness.
      // Borrowed from analytics.js (https://github.com/segment-integrations/analytics.js-integration-segmentio/blob/a20d2a2d222aeb3ab2a8c7e72280f1df2618440e/lib/index.js#L255-L256).
      message.messageId = `node-${md5(JSON.stringify(message))}-${uuid()}`
    }

Given that nobody should be running this library in a browser (or on a server without a good source of entropy), can't we just use a plain uuid() here?

I'm afraid to touch this, given that it'd be an actual functionality change, but I think you could probably shave some bytes off of your payloads, and squeeze out a few more CPU cycles if you got rid of the stringify/hashing here!

schmod avatar Oct 03 '22 19:10 schmod