From 1b18f0ba24eaa1e7530063975e64b333d1ed98ea Mon Sep 17 00:00:00 2001 From: Michael Niksa Date: Tue, 11 Jun 2024 10:58:17 -0700 Subject: [PATCH] Add ValueTuple based creation of CompressedColumnStorage to avoid Tuple allocations --- CSparse/Converter.cs | 20 ++++++++++++++++++++ CSparse/Storage/CompressedColumnStorage.cs | 10 ++++++++++ 2 files changed, 30 insertions(+) diff --git a/CSparse/Converter.cs b/CSparse/Converter.cs index 131cb91..4285117 100644 --- a/CSparse/Converter.cs +++ b/CSparse/Converter.cs @@ -289,5 +289,25 @@ public static CoordinateStorage FromEnumerable(IEnumerable + /// Convert a row major array to coordinate storage. + /// + /// Enumerates the entries of a matrix with value tuples. + /// Number of rows. + /// Number of columns. + /// Coordinate storage. + public static CoordinateStorage FromEnumerable(IEnumerable<(int, int, T)> enumerable, int rowCount, int columnCount) + where T : struct, IEquatable, IFormattable + { + var storage = new CoordinateStorage(rowCount, columnCount, Math.Max(rowCount, columnCount)); + + foreach (var item in enumerable) + { + storage.At(item.Item1, item.Item2, item.Item3); + } + + return storage; + } } } diff --git a/CSparse/Storage/CompressedColumnStorage.cs b/CSparse/Storage/CompressedColumnStorage.cs index e6a1b70..f5f81ad 100644 --- a/CSparse/Storage/CompressedColumnStorage.cs +++ b/CSparse/Storage/CompressedColumnStorage.cs @@ -153,6 +153,16 @@ public static CompressedColumnStorage OfIndexed(int rows, int columns, IEnume return Converter.ToCompressedColumnStorage(c); } + /// + /// Create a new sparse matrix as a copy of the given indexed enumerable using a value tuple. + /// + public static CompressedColumnStorage OfIndexed(int rows, int columns, IEnumerable<(int, int, T)> enumerable) + { + var c = Converter.FromEnumerable(enumerable, rows, columns); + + return Converter.ToCompressedColumnStorage(c); + } + /// /// Create a new sparse matrix as a copy of the given array (row-major). ///