Skip to content

Instantly share code, notes, and snippets.

@wendreof
Created April 16, 2024 01:39
Show Gist options
  • Save wendreof/8e99f0156d0b67440cffe041291cef50 to your computer and use it in GitHub Desktop.
Save wendreof/8e99f0156d0b67440cffe041291cef50 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
using BenchmarkDotNet.Attributes; // Library for benchmarking
using BenchmarkDotNet.Running; // Library for running benchmarks
using Newtonsoft.Json; // Library for JSON serialization
namespace JsonBenchmark
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public double Price { get; set; } // Price of the product
public string Category { get; set; } = string.Empty;
}
public class Program
{
static void Main(string[] args)
{
// Runs the benchmark defined in the JsonComparisons class
BenchmarkRunner.Run<JsonComparisons>();
}
}
// Benchmark class for comparing JSON serialization methods
[MemoryDiagnoser] // Enables memory diagnostics for benchmarks
[RankColumn] // Adds a column to display the rank of each benchmark
public class JsonComparisons
{
private readonly List<Product> _products; // List of products to be serialized
[Params(10, 100, 1000)] // Specifies different values for the number of products
public int NumberOfProducts { get; set; } // Parameter to control the number of products
// Constructor to initialize the list of products
public JsonComparisons()
{
_products = new List<Product>();
for (int i = 0; i < NumberOfProducts; i++)
{
// Populates the list of products with dummy data
_products.Add(new Product
{
Id = i + 1,
Name = $"Name {i + 1}",
Category = $"Category {i + 1}",
Description = $"Description {i + 1}",
Price = i + 1
});
}
}
// Benchmark method for serializing using Newtonsoft.Json
[Benchmark]
public string NewtonsoftSerialize() => JsonConvert.SerializeObject(_products);
// Benchmark method for serializing using System.Text.Json
[Benchmark]
public string SystemTextJsonSerialize() => System.Text.Json.JsonSerializer.Serialize(_products);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment