Skip to content

Instantly share code, notes, and snippets.

@ihordyrman
Created August 21, 2021 07:50
Show Gist options
  • Save ihordyrman/d2d23ad7498b40600ec6952580d425d9 to your computer and use it in GitHub Desktop.
Save ihordyrman/d2d23ad7498b40600ec6952580d425d9 to your computer and use it in GitHub Desktop.
Clousers
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
internal class Program
{
public static void Main()
{
var mem = MemoizeFunction<string, string>(GetWebPage);
Stopwatch stopwatch = new();
stopwatch.Start();
var result = mem("https://www.youtube.com/");
stopwatch.Stop();
Console.WriteLine($"First result length: {result.Length} | time: {stopwatch.ElapsedMilliseconds}");
stopwatch.Reset();
stopwatch.Start();
var result2 = mem("https://www.youtube.com/");
stopwatch.Stop();
Console.WriteLine($"Second result length: {result2.Length} | time: {stopwatch.ElapsedMilliseconds}");
stopwatch.Reset();
stopwatch.Start();
var result3 = mem("https://www.youtube.com/");
stopwatch.Stop();
Console.WriteLine($"Third result length: {result3.Length} | time: {stopwatch.ElapsedMilliseconds}");
stopwatch.Reset();
}
static Func<TIn, TOut> MemoizeFunction<TIn, TOut>(Func<TIn, TOut> func)
{
var cache = new Dictionary<TIn, TOut>();
return input => cache.TryGetValue(input, out var result)
? result
: cache[input] = func(input);
}
static string GetWebPage(string uri)
{
return new WebClient().DownloadString(uri);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment