Created
July 14, 2022 02:39
-
-
Save altbodhi/0e2f3731a039ce8b1ff0c85b3d81b191 to your computer and use it in GitHub Desktop.
Compare two equivalent of skip loop function with different paradigm: imperative and functional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Console; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
def skip_loop(counter, skip, max, idx, lst) { | |
if (idx > max) lst | |
else | |
if ( counter >= skip ) | |
skip_loop(1, skip, max, idx + 1, idx :: lst) | |
else | |
skip_loop(counter + 1, skip, max, idx + 1, lst) | |
}; | |
def skippedWhile (skip, max) { | |
mutable res = []; | |
mutable i = skip; | |
while (i <= max) { | |
res ::= i; | |
i = i + skip; | |
} | |
res.Rev() | |
}; | |
def maxValue = 1000_000; | |
def skipValue = 3; | |
def totalRun = 1000; | |
def benchmark (f) { | |
def sw = Stopwatch.StartNew(); | |
for(mutable i=0; i < totalRun; i++) | |
f(); | |
sw.Stop(); | |
sw.ElapsedMilliseconds / totalRun | |
} | |
def benchImp = benchmark( () => _ = skippedWhile(skipValue, maxValue)); | |
def benchRecu = benchmark( () => _ = skip_loop(1, skipValue, maxValue, 1, []).Rev()); | |
WriteLine($"imp = $benchImp\t rec = $benchRecu"); | |
//=> imp = 56 rec = 57 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
result on next time: imp = 64 rec = 59