Repository: dask/dask
Issue category: Performance Issue

Issue:
`NestedContainer.to_container` method gets tracked individually per NestedContainer object
Looking into https://github.com/dask/distributed/issues/8958, I've noticed that for each `NestedContainer` object, its bound `to_container` method is tracked individually by the GC. This accounts for ~500k of 9MM objects in my workload. It would probably be better to stop tracking these individually.


Hints:
On top, that is very likely a self referencing cycle so breaking this will benefit GC in more than one way

Patch:
diff --git a/dask/_task_spec.py b/dask/_task_spec.py
index 316f1805aa6..c108bbb5b6b 100644
--- a/dask/_task_spec.py
+++ b/dask/_task_spec.py
@@ -799,6 +799,7 @@ def __init__(
             None,
             self.to_container,
             *args,
+            klass=self.klass,
             _dependencies=_dependencies,
             **kwargs,
         )
@@ -832,9 +833,9 @@ def __dask_tokenize__(self):
 
         return super().__dask_tokenize__()
 
-    @classmethod
-    def to_container(cls, *args, **kwargs):
-        return cls.klass(args)
+    @staticmethod
+    def to_container(*args, klass):
+        return klass(args)
 
 
 class List(NestedContainer):


Test patch: