bkietz commented on a change in pull request #8716:
URL: https://github.com/apache/arrow/pull/8716#discussion_r577713086



##########
File path: cpp/src/arrow/util/cache_internal.h
##########
@@ -0,0 +1,232 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <cassert>
+#include <functional>
+#include <list>
+#include <memory>
+#include <mutex>
+#include <type_traits>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "arrow/util/functional.h"
+#include "arrow/util/macros.h"
+
+namespace arrow {
+namespace internal {
+
+// A LRU (Least recently used) replacement cache
+template <typename Key, typename Value>
+class LRUCache {
+ public:
+  explicit LRUCache(int32_t capacity) : capacity_(capacity) {
+    // The map size can temporarily exceed the cache capacity, see Replace()
+    map_.reserve(capacity_ + 1);
+  }
+
+  ARROW_DISALLOW_COPY_AND_ASSIGN(LRUCache);
+  ARROW_DEFAULT_MOVE_AND_ASSIGN(LRUCache);
+
+  void Clear() {
+    items_.clear();
+    map_.clear();
+    // The C++ spec doesn't tell whether map_.clear() will shrink the map 
capacity
+    map_.reserve(capacity_ + 1);
+  }
+
+  int32_t size() const {
+    assert(items_.size() == map_.size());
+    return static_cast<int32_t>(items_.size());
+  }
+
+  template <typename K>
+  Value* Find(K&& key) {
+    const auto it = map_.find(key);
+    if (it == map_.end()) {
+      return NULLPTR;
+    } else {
+      // Found => move item at front of the list
+      auto list_it = it->second;
+      items_.splice(items_.begin(), items_, list_it);
+      return &list_it->value;
+    }
+  }
+
+  template <typename K, typename V>
+  std::pair<bool, Value*> Replace(K&& key, V&& value) {
+    // Try to insert temporary iterator
+    auto pair = map_.emplace(std::forward<K>(key), ListIt{});
+    const auto it = pair.first;
+    const bool inserted = pair.second;
+    if (inserted) {
+      // Inserted => push item at front of the list, and update iterator
+      items_.push_front(Item{&it->first, std::forward<V>(value)});
+      it->second = items_.begin();
+      // Did we exceed the cache capacity?  If so, remove least recently used 
item
+      if (static_cast<int32_t>(items_.size()) > capacity_) {
+        const bool erased = map_.erase(*items_.back().key);
+        assert(erased);

Review comment:
       Since this is an `_internal` header, it's fine to use `DCHECK` and 
`nullptr` here

##########
File path: cpp/src/arrow/util/cache_internal.h
##########
@@ -0,0 +1,232 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <cassert>
+#include <functional>
+#include <list>
+#include <memory>
+#include <mutex>
+#include <type_traits>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "arrow/util/functional.h"
+#include "arrow/util/macros.h"
+
+namespace arrow {
+namespace internal {
+
+// A LRU (Least recently used) replacement cache
+template <typename Key, typename Value>
+class LRUCache {
+ public:
+  explicit LRUCache(int32_t capacity) : capacity_(capacity) {
+    // The map size can temporarily exceed the cache capacity, see Replace()
+    map_.reserve(capacity_ + 1);
+  }
+
+  ARROW_DISALLOW_COPY_AND_ASSIGN(LRUCache);
+  ARROW_DEFAULT_MOVE_AND_ASSIGN(LRUCache);
+
+  void Clear() {
+    items_.clear();
+    map_.clear();
+    // The C++ spec doesn't tell whether map_.clear() will shrink the map 
capacity
+    map_.reserve(capacity_ + 1);
+  }
+
+  int32_t size() const {
+    assert(items_.size() == map_.size());
+    return static_cast<int32_t>(items_.size());
+  }
+
+  template <typename K>
+  Value* Find(K&& key) {
+    const auto it = map_.find(key);
+    if (it == map_.end()) {
+      return NULLPTR;
+    } else {
+      // Found => move item at front of the list
+      auto list_it = it->second;
+      items_.splice(items_.begin(), items_, list_it);
+      return &list_it->value;
+    }
+  }
+
+  template <typename K, typename V>
+  std::pair<bool, Value*> Replace(K&& key, V&& value) {
+    // Try to insert temporary iterator
+    auto pair = map_.emplace(std::forward<K>(key), ListIt{});
+    const auto it = pair.first;
+    const bool inserted = pair.second;
+    if (inserted) {
+      // Inserted => push item at front of the list, and update iterator
+      items_.push_front(Item{&it->first, std::forward<V>(value)});
+      it->second = items_.begin();
+      // Did we exceed the cache capacity?  If so, remove least recently used 
item
+      if (static_cast<int32_t>(items_.size()) > capacity_) {
+        const bool erased = map_.erase(*items_.back().key);
+        assert(erased);
+        ARROW_UNUSED(erased);
+        items_.pop_back();
+      }
+      return {true, &it->second->value};
+    } else {
+      // Already exists => move item at front of the list, and update value
+      auto list_it = it->second;
+      items_.splice(items_.begin(), items_, list_it);
+      list_it->value = std::forward<V>(value);
+      return {false, &list_it->value};
+    }
+  }
+
+ private:
+  struct Item {
+    // Pointer to the key inside the unordered_map
+    const Key* key;
+    Value value;
+  };
+  using List = std::list<Item>;
+  using ListIt = typename List::iterator;
+
+  const int32_t capacity_;
+  // In most to least recently used order
+  std::list<Item> items_;
+  std::unordered_map<Key, ListIt> map_;
+};
+
+namespace detail {
+
+template <typename Key, typename Value, typename Cache, typename Func>
+struct ThreadSafeMemoizer {
+  using RetType = Value;
+
+  template <typename F>
+  ThreadSafeMemoizer(F&& func, int32_t cache_capacity)
+      : mutex_(new std::mutex), func_(std::forward<F>(func)), 
cache_(cache_capacity) {}
+
+  // The memoizer can't return a pointer to the cached value, because
+  // the cache entry may be evicted by another thread.
+
+  Value operator()(const Key& key) {
+    std::unique_lock<std::mutex> lock(*mutex_);
+    const Value* value_ptr;
+    value_ptr = cache_.Find(key);
+    if (ARROW_PREDICT_TRUE(value_ptr != NULLPTR)) {
+      return *value_ptr;
+    }
+    lock.unlock();
+    Value v = func_(key);
+    lock.lock();
+    return *cache_.Replace(key, std::move(v)).second;
+  }
+
+ private:
+  std::unique_ptr<std::mutex> mutex_;
+  Func func_;
+  Cache cache_;
+};
+
+template <typename Key, typename Value, typename Cache, typename Func>
+struct ThreadUnsafeMemoizer {
+  using RetType = const Value&;
+
+  template <typename F>
+  ThreadUnsafeMemoizer(F&& func, int32_t cache_capacity)
+      : /*mutex_(new std::mutex), */ func_(std::forward<F>(func)),
+        cache_(cache_capacity) {}
+
+  const Value& operator()(const Key& key) {
+    const Value* value_ptr;
+    value_ptr = cache_.Find(key);
+    if (ARROW_PREDICT_TRUE(value_ptr != NULLPTR)) {
+      return *value_ptr;
+    }
+    return *cache_.Replace(key, func_(key)).second;
+  }
+
+ private:
+  Func func_;
+  Cache cache_;
+};
+
+// A copy-constructible callable wrapper, for std::function<>
+
+template <typename Callable, typename RetType = 
call_traits::return_type<Callable>,
+          typename Value = call_traits::argument_type<0, Callable>>
+struct SharedCallable {
+  explicit SharedCallable(Callable callable)
+      : callable_(std::make_shared<Callable>(std::move(callable))) {}
+
+  template <typename V>
+  RetType operator()(V&& v) {
+    return (*callable_)(std::forward<V>(v));
+  }
+
+ private:
+  const std::shared_ptr<Callable> callable_;
+};
+
+template <template <typename...> class Cache,
+          template <typename...> class MemoizerType = ThreadSafeMemoizer, 
typename Func,
+          typename Key = typename std::decay<call_traits::argument_type<0, 
Func>>::type,
+          typename Value = typename 
std::decay<call_traits::return_type<Func>>::type,
+          typename Memoizer = MemoizerType<Key, Value, Cache<Key, Value>, 
Func>,

Review comment:
       This allows a memoizer to wrap the instance of `Func` by reference, 
which I think will be surprising. I've assembled an alternative in 
https://github.com/pitrou/arrow/pull/7

##########
File path: cpp/src/arrow/util/cache_benchmark.cc
##########
@@ -0,0 +1,146 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#include "benchmark/benchmark.h"
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+#include "arrow/array.h"
+#include "arrow/testing/random.h"
+#include "arrow/util/cache_internal.h"
+#include "arrow/util/checked_cast.h"
+#include "arrow/util/logging.h"
+#include "arrow/util/macros.h"
+
+namespace arrow {
+namespace internal {
+
+static constexpr int32_t kCacheSize = 100;
+static constexpr int32_t kSmallKeyLength = 8;
+static constexpr int32_t kLargeKeyLength = 64;
+static constexpr int32_t kSmallValueLength = 16;
+static constexpr int32_t kLargeValueLength = 1024;
+
+static std::vector<std::string> MakeStrings(int64_t nvalues, int64_t 
min_length,
+                                            int64_t max_length) {
+  auto rng = ::arrow::random::RandomArrayGenerator(42);
+  auto arr = checked_pointer_cast<StringArray>(rng.String(
+      nvalues, static_cast<int32_t>(min_length), 
static_cast<int32_t>(max_length)));
+  std::vector<std::string> vec(nvalues);
+  for (int64_t i = 0; i < nvalues; ++i) {
+    vec[i] = arr->GetString(i);
+  }
+  return vec;
+}
+
+static std::vector<std::string> MakeStrings(int64_t nvalues, int64_t length) {
+  return MakeStrings(nvalues, length, length);
+}
+
+template <typename Cache, typename Key, typename Value>
+static void BenchmarkCacheLookups(benchmark::State& state, const 
std::vector<Key>& keys,
+                                  const std::vector<Value>& values) {
+  const int32_t nitems = static_cast<int32_t>(keys.size());
+  Cache cache(nitems);
+  for (int32_t i = 0; i < nitems; ++i) {
+    cache.Replace(keys[i], values[i]);
+  }
+
+  for (auto _ : state) {
+    int64_t nfinds = 0;
+    for (const auto& key : keys) {
+      nfinds += (cache.Find(key) != nullptr);
+    }
+    benchmark::DoNotOptimize(nfinds);
+    ARROW_CHECK_EQ(nfinds, nitems);
+  }
+  state.SetItemsProcessed(state.iterations() * nitems);
+}
+
+static void LRUCacheLookup(benchmark::State& state) {
+  const auto keys = MakeStrings(kCacheSize, state.range(0));
+  const auto values = MakeStrings(kCacheSize, state.range(1));
+  BenchmarkCacheLookups<LRUCache<std::string, std::string>>(state, keys, 
values);
+}
+
+static void SetCacheArgs(benchmark::internal::Benchmark* bench) {
+  bench->Args({kSmallKeyLength, kSmallValueLength});
+  bench->Args({kSmallKeyLength, kLargeValueLength});
+  bench->Args({kLargeKeyLength, kSmallValueLength});
+  bench->Args({kLargeKeyLength, kLargeValueLength});
+}
+
+BENCHMARK(LRUCacheLookup)->Apply(SetCacheArgs);
+
+struct Callable {
+  explicit Callable(std::vector<std::string> values)
+      : index_(0), values_(std::move(values)) {}
+
+  std::string operator()(const std::string& key) {
+    // Return a value unrelated to the key
+    if (++index_ >= static_cast<int64_t>(values_.size())) {
+      index_ = 0;
+    }
+    return values_[index_];
+  }
+
+ private:
+  int64_t index_;
+  std::vector<std::string> values_;
+};
+
+template <typename Memoized>
+static void BenchmarkMemoize(benchmark::State& state, Memoized&& mem,
+                             const std::vector<std::string>& keys) {
+  // Prime memoization cache
+  for (const auto& key : keys) {
+    mem(key);
+  }
+
+  for (auto _ : state) {
+    int64_t nbytes = 0;
+    for (const auto& key : keys) {
+      nbytes += static_cast<int64_t>(mem(key).length());
+    }
+    benchmark::DoNotOptimize(nbytes);
+  }
+  state.SetItemsProcessed(state.iterations() * keys.size());
+}
+
+static void MemoizeLRUCached(benchmark::State& state) {
+  const auto keys = MakeStrings(kCacheSize, state.range(0));
+  const auto values = MakeStrings(kCacheSize, state.range(1));

Review comment:
       I'd also be interested to see benchmarks where the size of the string 
set is `kCacheSize * [0.5, 0.9, 1.1, 2]`

##########
File path: cpp/src/arrow/util/cache_internal.h
##########
@@ -0,0 +1,232 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+#pragma once
+
+#include <cassert>
+#include <functional>
+#include <list>
+#include <memory>
+#include <mutex>
+#include <type_traits>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "arrow/util/functional.h"
+#include "arrow/util/macros.h"
+
+namespace arrow {
+namespace internal {
+
+// A LRU (Least recently used) replacement cache
+template <typename Key, typename Value>
+class LRUCache {
+ public:
+  explicit LRUCache(int32_t capacity) : capacity_(capacity) {
+    // The map size can temporarily exceed the cache capacity, see Replace()
+    map_.reserve(capacity_ + 1);
+  }
+
+  ARROW_DISALLOW_COPY_AND_ASSIGN(LRUCache);
+  ARROW_DEFAULT_MOVE_AND_ASSIGN(LRUCache);
+
+  void Clear() {
+    items_.clear();
+    map_.clear();
+    // The C++ spec doesn't tell whether map_.clear() will shrink the map 
capacity
+    map_.reserve(capacity_ + 1);
+  }
+
+  int32_t size() const {
+    assert(items_.size() == map_.size());
+    return static_cast<int32_t>(items_.size());
+  }
+
+  template <typename K>
+  Value* Find(K&& key) {
+    const auto it = map_.find(key);
+    if (it == map_.end()) {
+      return NULLPTR;
+    } else {
+      // Found => move item at front of the list
+      auto list_it = it->second;
+      items_.splice(items_.begin(), items_, list_it);
+      return &list_it->value;
+    }
+  }
+
+  template <typename K, typename V>
+  std::pair<bool, Value*> Replace(K&& key, V&& value) {
+    // Try to insert temporary iterator
+    auto pair = map_.emplace(std::forward<K>(key), ListIt{});
+    const auto it = pair.first;
+    const bool inserted = pair.second;
+    if (inserted) {
+      // Inserted => push item at front of the list, and update iterator
+      items_.push_front(Item{&it->first, std::forward<V>(value)});
+      it->second = items_.begin();
+      // Did we exceed the cache capacity?  If so, remove least recently used 
item
+      if (static_cast<int32_t>(items_.size()) > capacity_) {
+        const bool erased = map_.erase(*items_.back().key);
+        assert(erased);
+        ARROW_UNUSED(erased);
+        items_.pop_back();
+      }
+      return {true, &it->second->value};
+    } else {
+      // Already exists => move item at front of the list, and update value
+      auto list_it = it->second;
+      items_.splice(items_.begin(), items_, list_it);
+      list_it->value = std::forward<V>(value);
+      return {false, &list_it->value};
+    }
+  }
+
+ private:
+  struct Item {
+    // Pointer to the key inside the unordered_map
+    const Key* key;
+    Value value;
+  };
+  using List = std::list<Item>;
+  using ListIt = typename List::iterator;
+
+  const int32_t capacity_;
+  // In most to least recently used order
+  std::list<Item> items_;
+  std::unordered_map<Key, ListIt> map_;
+};
+
+namespace detail {
+
+template <typename Key, typename Value, typename Cache, typename Func>
+struct ThreadSafeMemoizer {
+  using RetType = Value;
+
+  template <typename F>
+  ThreadSafeMemoizer(F&& func, int32_t cache_capacity)
+      : mutex_(new std::mutex), func_(std::forward<F>(func)), 
cache_(cache_capacity) {}
+
+  // The memoizer can't return a pointer to the cached value, because
+  // the cache entry may be evicted by another thread.
+
+  Value operator()(const Key& key) {
+    std::unique_lock<std::mutex> lock(*mutex_);
+    const Value* value_ptr;
+    value_ptr = cache_.Find(key);
+    if (ARROW_PREDICT_TRUE(value_ptr != NULLPTR)) {
+      return *value_ptr;
+    }
+    lock.unlock();
+    Value v = func_(key);
+    lock.lock();
+    return *cache_.Replace(key, std::move(v)).second;
+  }
+
+ private:
+  std::unique_ptr<std::mutex> mutex_;
+  Func func_;
+  Cache cache_;
+};
+
+template <typename Key, typename Value, typename Cache, typename Func>
+struct ThreadUnsafeMemoizer {
+  using RetType = const Value&;
+
+  template <typename F>
+  ThreadUnsafeMemoizer(F&& func, int32_t cache_capacity)
+      : /*mutex_(new std::mutex), */ func_(std::forward<F>(func)),
+        cache_(cache_capacity) {}
+
+  const Value& operator()(const Key& key) {
+    const Value* value_ptr;
+    value_ptr = cache_.Find(key);
+    if (ARROW_PREDICT_TRUE(value_ptr != NULLPTR)) {
+      return *value_ptr;
+    }
+    return *cache_.Replace(key, func_(key)).second;
+  }
+
+ private:
+  Func func_;
+  Cache cache_;
+};
+
+// A copy-constructible callable wrapper, for std::function<>
+
+template <typename Callable, typename RetType = 
call_traits::return_type<Callable>,
+          typename Value = call_traits::argument_type<0, Callable>>
+struct SharedCallable {
+  explicit SharedCallable(Callable callable)
+      : callable_(std::make_shared<Callable>(std::move(callable))) {}
+
+  template <typename V>
+  RetType operator()(V&& v) {
+    return (*callable_)(std::forward<V>(v));
+  }
+
+ private:
+  const std::shared_ptr<Callable> callable_;
+};
+
+template <template <typename...> class Cache,
+          template <typename...> class MemoizerType = ThreadSafeMemoizer, 
typename Func,
+          typename Key = typename std::decay<call_traits::argument_type<0, 
Func>>::type,
+          typename Value = typename 
std::decay<call_traits::return_type<Func>>::type,
+          typename Memoizer = MemoizerType<Key, Value, Cache<Key, Value>, 
Func>,
+          typename RetFunc = std::function<typename Memoizer::RetType(const 
Key&)>>
+static RetFunc Memoize(Func&& func, int32_t cache_capacity) {
+  return SharedCallable<Memoizer>(Memoizer(std::forward<Func>(func), 
cache_capacity));
+}
+
+// template <template <typename K, typename V> class Cache,
+//           template <typename K, typename V, typename C, typename F>
+//           class MemoizerType = ThreadSafeMemoizer,
+//           typename Func,
+//           typename Key = typename std::decay<call_traits::argument_type<0,
+//           Func>>::type, typename Value = typename
+//           std::decay<call_traits::return_type<Func>>::type, typename 
Memoizer =
+//           MemoizerType<Key, Value, Cache<Key, Value>, Func>, typename 
RetFunc =
+//           Memoizer>
+// static RetFunc Memoize(Func&& func, int32_t cache_capacity) {
+//   return Memoizer(std::forward<Func>(func), cache_capacity);
+// }

Review comment:
       ```suggestion
   ```




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to