Skip to content

Performance decrease when called from anonymous function #347

@v-kuropatka

Description

@v-kuropatka

I noticed some strange behavior when JSON.Serialize is called via anonymous function. Consider following benchmark:

    [MemoryDiagnoser]
    public class SerializersBenchmark
    {
        private Action<object> jilSerializer = o => JSON.Serialize(o, Options.ISO8601);
        private static readonly SomePerson Person = new SomePerson
        {
            FirstName =  "John",
            LastName = "Doe"
        };

        [Benchmark]
        public void JilSerializer()
        {
            JSON.Serialize(Person, Options.ISO8601);
        }

        [Benchmark]
        public void JilSerializerThroughAction()
        {
            jilSerializer(Person);
        }

        public class SomePerson
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
    }

Here are results:

Method Mean Error StdDev Gen 0 Gen 1 Gen 2 Allocated
JilSerializer 260.8 ns 1.61 ns 1.43 ns 0.0525 - - 440 B
JilSerializerThroughAction 447.5 ns 2.87 ns 2.69 ns 0.0677 - - 568 B

You can see significant performance reduction and increase of memory allocation. Could you please advise how to avoid it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions