From 3a6322f7c649ab7ce9c61d6cf8475b8376151d12 Mon Sep 17 00:00:00 2001 From: h7x4 Date: Fri, 27 Sep 2024 22:32:11 +0200 Subject: [PATCH] fix/add expected time complexity comments --- src/genAttrs.nix | 3 +++ src/getAttrs.nix | 5 +++++ src/subtractLists.nix | 6 +++--- src/unique.nix | 1 + 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/genAttrs.nix b/src/genAttrs.nix index 2aff6e3..f4eb83a 100644 --- a/src/genAttrs.nix +++ b/src/genAttrs.nix @@ -1,6 +1,9 @@ lib: let + # O(n * f) genAttrsOld = names: f: lib.listToAttrs (map (n: lib.nameValuePair n (f n)) names); + + # O(n * f) genAttrsNew = names: f: lib.listToAttrs (map (n: { name = n; value = f n; }) names); bigdata = lib.imap0 (i: _: toString i) (lib.replicate 999999 null); diff --git a/src/getAttrs.nix b/src/getAttrs.nix index 57dc1af..fce4ff5 100644 --- a/src/getAttrs.nix +++ b/src/getAttrs.nix @@ -1,7 +1,12 @@ lib: let + # O(n)? (assuming `name: attrs.${name}` is O(1)) getAttrsOld = names: attrs: lib.genAttrs names (name: attrs.${name}); + + # O(n^2) getAttrsNew1 = names: attrs: lib.filterAttrs (n: _: builtins.elem n names) attrs; + + # O(n log m) (where m is the larger attrset, i.e. `attrs` in this case) getAttrsNew2 = names: attrs: builtins.intersectAttrs (lib.genAttrs names (_: null)) attrs; bigdata = lib.genAttrs (lib.imap0 (i: _: toString i) (lib.replicate 999999 null)) (_: null); diff --git a/src/subtractLists.nix b/src/subtractLists.nix index 9d1cf9b..b5e0d2e 100644 --- a/src/subtractLists.nix +++ b/src/subtractLists.nix @@ -1,13 +1,13 @@ lib: let - # O(nm) + # O(n * m) subtractListsOld = e: builtins.filter (x: !(builtins.elem x e)); # O(n + m) (hopefully) subtractListsNew = e: let - # Assuming genAttrs is O(n) + # Assuming genAttrs is O(n * f) and f = (_: null) is O(1), so O(n) in total e' = lib.genAttrs e (_: null); - # Assuming hasAttr is O(1) + # Assuming `filter` is O(n) and `hasAttr` is O(1) in builtins.filter (x: !(builtins.hasAttr x e')); bigdata = lib.imap0 (i: _: toString i) (lib.replicate 999999 null); diff --git a/src/unique.nix b/src/unique.nix index 22db49b..d77380a 100644 --- a/src/unique.nix +++ b/src/unique.nix @@ -1,5 +1,6 @@ lib: let + # O(n^2), assuming foldl' is O(n) and ++ causes a reallocation every time uniqueOld = builtins.foldl' (acc: e: if builtins.elem e acc then acc else acc ++ [ e ]) []; # uniqueNew = xs: let # entries = lib.genAttrs xs (_: null);