diff options
| author | Utkarsh Kukreti <[email protected]> | 2014-04-28 12:11:40 +0530 |
|---|---|---|
| committer | Utkarsh Kukreti <[email protected]> | 2014-04-28 12:14:15 +0530 |
| commit | 6e9a088efbe678c93310cb22eb6612434b9f7a09 (patch) | |
| tree | 9ccbb7cb9568f496642e8b93309686c50527d2a2 /mrbgems/mruby-array-ext/mrblib/array.rb | |
| parent | 220f3124b9bd7a993e78b5832d0501209236487f (diff) | |
| download | mruby-6e9a088efbe678c93310cb22eb6612434b9f7a09.tar.gz mruby-6e9a088efbe678c93310cb22eb6612434b9f7a09.zip | |
Speed up Array#select! from O(n^2) to O(n).
Diffstat (limited to 'mrbgems/mruby-array-ext/mrblib/array.rb')
| -rw-r--r-- | mrbgems/mruby-array-ext/mrblib/array.rb | 15 |
1 files changed, 5 insertions, 10 deletions
diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index bddcd8ab8..3a4b1460b 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -675,16 +675,11 @@ class Array def select!(&block) return to_enum :select! unless block_given? - idx = 0 - len = self.size - while idx < self.size do - if block.call(self[idx]) - idx += 1 - else - self.delete_at(idx) - end + result = [] + self.each do |x| + result << x if block.call(x) end - return nil if self.size == len - self + return nil if self.size == result.size + self.replace(result) end end |
