From 73ddfa25b41ddf475b70b7089e3b4d2402494f01 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Sun, 9 Feb 2020 15:51:03 +0100 Subject: Optimize hashing of floating point numbers Change-Id: Id5e091b135c006b10987f229f45319228edb8675 Reviewed-by: Thiago Macieira Reviewed-by: Fabian Kosmale --- src/corelib/tools/qhash.cpp | 25 ++++++++++++++++--------- src/corelib/tools/qhashfunctions.h | 9 ++++++++- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/corelib/tools/qhash.cpp b/src/corelib/tools/qhash.cpp index 4c62f6b160..97dda58748 100644 --- a/src/corelib/tools/qhash.cpp +++ b/src/corelib/tools/qhash.cpp @@ -769,17 +769,12 @@ uint qt_hash(QStringView key, uint chained) noexcept Returns the hash value for the \a key, using \a seed to seed the calculation. */ -/*! \relates QHash +/*! \fn size_t qHash(float key, size_t seed) noexcept + \relates QHash \since 5.3 Returns the hash value for the \a key, using \a seed to seed the calculation. */ -size_t qHash(float key, size_t seed) noexcept -{ - // ensure -0 gets mapped to 0 - key += 0.0f; - return murmurhash(&key, sizeof(key), seed); -} /*! \relates QHash \since 5.3 @@ -790,7 +785,13 @@ size_t qHash(double key, size_t seed) noexcept { // ensure -0 gets mapped to 0 key += 0.0; - return murmurhash(&key, sizeof(key), seed); + if constexpr (sizeof(double) == sizeof(size_t)) { + size_t k; + memcpy(&k, &key, sizeof(double)); + return QHashPrivate::hash(k, seed); + } else { + return murmurhash(&key, sizeof(key), seed); + } } #if !defined(Q_OS_DARWIN) || defined(Q_CLANG_QDOC) @@ -803,7 +804,13 @@ size_t qHash(long double key, size_t seed) noexcept { // ensure -0 gets mapped to 0 key += static_cast(0.0); - return murmurhash(&key, sizeof(key), seed); + if constexpr (sizeof(long double) == sizeof(size_t)) { + size_t k; + memcpy(&k, &key, sizeof(long double)); + return QHashPrivate::hash(k, seed); + } else { + return murmurhash(&key, sizeof(key), seed); + } } #endif diff --git a/src/corelib/tools/qhashfunctions.h b/src/corelib/tools/qhashfunctions.h index f519925798..ef83682433 100644 --- a/src/corelib/tools/qhashfunctions.h +++ b/src/corelib/tools/qhashfunctions.h @@ -120,7 +120,14 @@ Q_DECL_CONST_FUNCTION Q_DECL_CONSTEXPR inline size_t qHash(quint64 key, size_t s return QHashPrivate::hash(size_t(key), seed); } Q_DECL_CONST_FUNCTION constexpr inline size_t qHash(qint64 key, size_t seed = 0) noexcept { return qHash(quint64(key), seed); } -Q_CORE_EXPORT Q_DECL_CONST_FUNCTION size_t qHash(float key, size_t seed = 0) noexcept; +Q_DECL_CONST_FUNCTION inline size_t qHash(float key, size_t seed = 0) noexcept +{ + // ensure -0 gets mapped to 0 + key += 0.0f; + uint k; + memcpy(&k, &key, sizeof(float)); + return QHashPrivate::hash(k, seed); +} Q_CORE_EXPORT Q_DECL_CONST_FUNCTION size_t qHash(double key, size_t seed = 0) noexcept; #if !defined(Q_OS_DARWIN) || defined(Q_CLANG_QDOC) Q_CORE_EXPORT Q_DECL_CONST_FUNCTION size_t qHash(long double key, size_t seed = 0) noexcept; -- cgit v1.2.3