Skip to content

ConcurrentChain: Optimize Load method#1314

Merged
NicolasDorier merged 7 commits into
MetacoSA:masterfrom
Carti-it:ConcurrentChain-optimization-2b
Jun 15, 2026
Merged

ConcurrentChain: Optimize Load method#1314
NicolasDorier merged 7 commits into
MetacoSA:masterfrom
Carti-it:ConcurrentChain-optimization-2b

Conversation

@Carti-it

@Carti-it Carti-it commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

This PR optimizes ConcurrentChain(byte[] bytes) method by removing LINQ use and using a simple while loop. On my machine, it translates to ~14% improvement when using the constructor.

Benchmark

I started Wasabi (WalletWasabi/WalletWasabi@b28faaf) and it generates WalletWasabi/Client/BitcoinP2pNetwork/BlockHeadersMain.dat (~104 MB) and used that file for benchmarking purposes (benchmark was added in 920bb36 and removed in 7116978):

using BenchmarkDotNet.Attributes;
using System;
using System.IO;

namespace NBitcoin.Bench;

public class ConcurrentChainBench
{
	byte[] Bytes; 

	[GlobalSetup]
	public void Setup()
	{
		var appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WalletWasabi", "Client", "BitcoinP2pNetwork", "BlockHeadersMain.dat");
		Bytes = File.ReadAllBytes(appDataPath);
	}

	[Benchmark]
	public void WriteToString()
	{
		var chain = new ConcurrentChain(Bytes, Network.Main.Consensus.ConsensusFactory);
	}
}
cd NBitcoin.Bench
dotnet run -c Release -- --runtimes net8.0 --filter *ConcurrentChainBench*

master:

Method Mean Error StdDev
WriteToString 1.507 s 0.0298 s 0.0306 s

PR:

Method Mean Error StdDev
WriteToString 1.299 s 0.0214 s 0.0189 s

So it's about 200 ms faster, or 14% faster.

In a way, I believe that Wasabi should optimize the header chain loading differently. However, given I spent some time with this, I figured it may be worth a PR.

@NicolasDorier

Copy link
Copy Markdown
Collaborator

Checking... but I think that people should avoid having to get the ConcurrentChain, because it is taking way too much memory in general.

@NicolasDorier NicolasDorier merged commit 8315c06 into MetacoSA:master Jun 15, 2026
6 checks passed
@Carti-it Carti-it deleted the ConcurrentChain-optimization-2b branch June 15, 2026 06:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants