Skip to content

Commit

Permalink
Allow setting default capacity for StringPool (crystal-lang#7899)
Browse files Browse the repository at this point in the history
* Allow setting default capacity for StringPool

* Typo in string_pool_spec

Co-Authored-By: Ary Borenszweig <asterite@gmail.com>
  • Loading branch information
2 people authored and dnamsons committed Jan 10, 2020
1 parent cdd0781 commit 4d0cbc7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
8 changes: 8 additions & 0 deletions spec/std/string_pool_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,12 @@ describe StringPool do
end
pool.size.should eq(10_000)
end

it "can be created with larger initial capacity" do
pool = StringPool.new(initial_capacity: 32)
s1 = pool.get "foo"
s2 = pool.get "foo"
s1.should be(s2)
pool.size.should eq(1)
end
end
14 changes: 12 additions & 2 deletions src/string_pool.cr
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,18 @@ class StringPool
getter size : Int32

# Creates a new empty string pool.
def initialize
@capacity = 8
#
# The *initial_capacity* is useful to avoid unnecessary reallocations
# of the internal buffers in case of growth. If you have an estimate
# of the maximum number of elements the pool will hold it should
# be initialized with that capacity for improved performance.
#
# ```
# pool = StringPool.new(256)
# pool.size # => 0
# ```
def initialize(initial_capacity = 8)
@capacity = initial_capacity
@hashes = Pointer(UInt64).malloc(@capacity, 0_u64)
@values = Pointer(String).malloc(@capacity, "")
@size = 0
Expand Down

0 comments on commit 4d0cbc7

Please sign in to comment.