Skip to content

Commit 7dc2f40

Browse files
authored
Performance: Reduce the time complexity of all Faker::Crypto methods (#2938)
* Reduce the time complexity of all Faker::Crypto methods * Store crypto lorem number of characters in a class constant
1 parent 41f620d commit 7dc2f40

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

lib/faker/default/crypto.rb

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,15 @@
55
module Faker
66
class Crypto < Base
77
class << self
8+
# Setting the lorem character number lower than the default of
9+
# 255 reduces the time complexity of each hash algorithm while
10+
# still returning deterministically unique values. See
11+
# https://github.com/faker-ruby/faker/pull/2938 for more info.
12+
MD5_MIN_NUMBER_OF_CHARACTERS = 25
13+
SHA1_MIN_NUMBER_OF_CHARACTERS = 31
14+
SHA256_MIN_NUMBER_OF_CHARACTERS = 50
15+
SHA512_MIN_NUMBER_OF_CHARACTERS = 100
16+
817
##
918
# Produces an MD5 hash.
1019
#
@@ -15,7 +24,7 @@ class << self
1524
#
1625
# @faker.version 1.6.4
1726
def md5
18-
OpenSSL::Digest::MD5.hexdigest(Lorem.characters)
27+
OpenSSL::Digest::MD5.hexdigest(Lorem.characters(number: MD5_MIN_NUMBER_OF_CHARACTERS))
1928
end
2029

2130
##
@@ -28,7 +37,7 @@ def md5
2837
#
2938
# @faker.version 1.6.4
3039
def sha1
31-
OpenSSL::Digest::SHA1.hexdigest(Lorem.characters)
40+
OpenSSL::Digest::SHA1.hexdigest(Lorem.characters(number: SHA1_MIN_NUMBER_OF_CHARACTERS))
3241
end
3342

3443
##
@@ -41,7 +50,7 @@ def sha1
4150
#
4251
# @faker.version 1.6.4
4352
def sha256
44-
OpenSSL::Digest::SHA256.hexdigest(Lorem.characters)
53+
OpenSSL::Digest::SHA256.hexdigest(Lorem.characters(number: SHA256_MIN_NUMBER_OF_CHARACTERS))
4554
end
4655

4756
##
@@ -54,7 +63,7 @@ def sha256
5463
#
5564
# @faker.version next
5665
def sha512
57-
OpenSSL::Digest::SHA512.hexdigest(Lorem.characters)
66+
OpenSSL::Digest::SHA512.hexdigest(Lorem.characters(number: SHA512_MIN_NUMBER_OF_CHARACTERS))
5867
end
5968
end
6069
end

0 commit comments

Comments
 (0)