Avoid allocs in dtors in futures collect
authorYedidya Feldblum <yfeldblum@fb.com>
Wed, 3 Jan 2018 21:41:22 +0000 (13:41 -0800)
committerFacebook Github Bot <facebook-github-bot@users.noreply.github.com>
Wed, 3 Jan 2018 21:57:24 +0000 (13:57 -0800)
Summary:
[Folly] Avoid allocs in dtors in futures `collect`.

`CollectContext`, a detail helper type, allocates storage for a results vector in its dtor. This is an awkward situation and should be avoided.

Reviewed By: ericniebler

Differential Revision: D6649299

fbshipit-source-id: 87746fcc78fa080f63505d7bb864aca6c4a3d7cb

folly/futures/Future-inl.h

index 56b98410abcfe59d24cfcdbe89caecf08a0d8ba2..cb94e037e2bb9f2f635f31f1aeb281ef52280472 100644 (file)
@@ -953,12 +953,12 @@ struct CollectContext {
     Nothing,
     std::vector<Optional<T>>>::type;
 
-  explicit CollectContext(size_t n) : result(n) {}
+  explicit CollectContext(size_t n) : result(n) {
+    finalResult.reserve(n);
+  }
   ~CollectContext() {
     if (!threw.exchange(true)) {
       // map Optional<T> -> T
-      std::vector<T> finalResult;
-      finalResult.reserve(result.size());
       std::transform(result.begin(), result.end(),
                      std::back_inserter(finalResult),
                      [](Optional<T>& o) { return std::move(o.value()); });
@@ -970,6 +970,7 @@ struct CollectContext {
   }
   Promise<Result> p;
   InternalResult result;
+  Result finalResult;
   std::atomic<bool> threw {false};
 };