Skip to content

Pooled arrays for tags? #196

@corentinaltepe

Description

@corentinaltepe

Hello,

All documentation instanciate a new string array for tags every time we need to increment a metrics counter. Example:

service.Increment("example_metric.increment", tags: new[] { "environment:dev" });

I'd like to limit the array allocations in order to limit stress to the GC. When possible, I set tags as static readonly, for example:

private static readonly string[] _myTags = ["environment:dev"];

public void DoSomething() {
  service.Increment("example_metric.increment", tags: _myTags);
}

It's often not possible to use a static array of tags. Is it possible to recycle an array of tags to multiple calls to service.Increment with different values of the tags, for example as follows ?

// Re-use an array of tags, but change the value of one of the tags
public void DoSomething() {
  var myTags = ["environment:dev", "myTag:A"];
  service.Increment("example_metric.increment", tags: _myTags);

  // Change the value of the second tag
  myTags[1] = "myTag:B";
  service.Increment("example_metric.increment", tags: _myTags);
}

// Borrow the tags array from a pool
public void DoSomethingElse() {
  var myTags = ArrayPool<string>.Shared.Rent(2);
  
  myTags[0] = "environment:dev";
  myTags[1] = "myTag:A";
  service.Increment("example_metric.increment", tags: _myTags);

  ArrayPool<string>.Shared.Return(myTags);
}

I'm afraid the tags arrays are processed (serialized) asynchronously, which mean we must ensure the array is not modified after a call to service.Increment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions