Skip to content

Commit

Permalink
apply f# optimization. Use array for faster reads
Browse files Browse the repository at this point in the history
  • Loading branch information
jinyus committed Oct 5, 2023
1 parent e85fbbf commit 08bec5f
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions csharp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
Expand All @@ -7,20 +8,28 @@

var sw = Stopwatch.StartNew();

var tagMap = new Dictionary<string, List<int>>();
// slower when int[] is used
var tagMapTemp = new Dictionary<string, Stack<int>>();

for (var i = 0; i < posts!.Count; i++)
{
foreach (var tag in posts[i].Tags)
{
if (!tagMap.ContainsKey(tag))
if (!tagMapTemp.ContainsKey(tag))
{
tagMap[tag] = new List<int>();
tagMapTemp[tag] = new Stack<int>();
}
tagMap[tag].Add(i);
tagMapTemp[tag].Push(i);
}
}

var tagMap = new Dictionary<string, int[]>();

foreach (var (tag, postIds) in tagMapTemp)
{
tagMap[tag] = postIds.ToArray();
}

var allRelatedPosts = new RelatedPosts[posts.Count];
var taggedPostCount = new int[posts.Count];

Expand Down Expand Up @@ -96,7 +105,7 @@ public struct Post
public required string Title { get; set; }

[JsonPropertyName("tags")]
public required List<string> Tags { get; set; }
public required string[] Tags { get; set; }
}

public struct RelatedPosts
Expand All @@ -105,7 +114,7 @@ public struct RelatedPosts
public required string Id { get; set; }

[JsonPropertyName("tags")]
public required List<string> Tags { get; set; }
public required string[] Tags { get; set; }

[JsonPropertyName("related")]
public required Post[] Related { get; set; }
Expand Down

0 comments on commit 08bec5f

Please sign in to comment.