Commit d6d84f34 authored by Pranjal Raihan's avatar Pranjal Raihan Committed by Facebook GitHub Bot

Use compact_once_flag in DelayedInit only if size can be reduced

Summary: If `T` is greater than 4-byte aligned, then `compact_once_flag` brings no size improvements. We can use `once_flag` in these cases, which has a better mutex (`folly::SharedMutex` rather than `folly::MicroLock`).

Reviewed By: yfeldblum

Differential Revision: D26214262

fbshipit-source-id: ea15376ea892df42cc9d3a6eac3da458fe0564a8
parent eb1954c7
...@@ -149,11 +149,16 @@ struct DelayedInit { ...@@ -149,11 +149,16 @@ struct DelayedInit {
} }
} }
using OnceFlag = std::conditional_t<
alignof(T) >= sizeof(once_flag),
once_flag,
compact_once_flag>;
struct StorageTriviallyDestructible { struct StorageTriviallyDestructible {
union { union {
std::remove_const_t<T> value; std::remove_const_t<T> value;
}; };
compact_once_flag init; OnceFlag init;
StorageTriviallyDestructible() {} StorageTriviallyDestructible() {}
}; };
...@@ -162,7 +167,7 @@ struct DelayedInit { ...@@ -162,7 +167,7 @@ struct DelayedInit {
union { union {
std::remove_const_t<T> value; std::remove_const_t<T> value;
}; };
compact_once_flag init; OnceFlag init;
StorageNonTriviallyDestructible() {} StorageNonTriviallyDestructible() {}
~StorageNonTriviallyDestructible() { ~StorageNonTriviallyDestructible() {
......
...@@ -232,6 +232,26 @@ TEST(DelayedInit, ConstType) { ...@@ -232,6 +232,26 @@ TEST(DelayedInit, ConstType) {
EXPECT_EQ(lazy->value, 12); EXPECT_EQ(lazy->value, 12);
} }
namespace {
template <typename T>
class DelayedInitSizeTest : public testing::Test {};
template <typename T>
struct WithOneByte {
T t;
char c;
};
} // namespace
using DelayedInitSizeTestTypes =
testing::Types<char, short, int, long, long long, char[3], short[2]>;
TYPED_TEST_CASE(DelayedInitSizeTest, DelayedInitSizeTestTypes);
TYPED_TEST(DelayedInitSizeTest, Size) {
// DelayedInit should not add more than 1-byte size overhead (modulo padding)
EXPECT_EQ(sizeof(DelayedInit<TypeParam>), sizeof(WithOneByte<TypeParam>));
}
TEST(DelayedInit, Concurrent) { TEST(DelayedInit, Concurrent) {
CtorCounts counts; CtorCounts counts;
DelayedInit<CtorCounts::Tracker> lazy; DelayedInit<CtorCounts::Tracker> lazy;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment