gpt4 book ai didi

mysql - Ruby Array - 计算重叠的快速方法

转载 作者:太空宇宙 更新时间:2023-11-03 17:39:09 25 4
gpt4 key购买 nike

我在我的一个模型中使用序列化数组字段,特别是计算每个数组的共享成员数。

现在,根据我的项目的性质,我不得不计算大量的这些重叠。所以我想知道是否有一种 super 快速、简洁的方法来做到这一点。

目前,我正在使用“&”方法,所以我的代码如下所示

(user1.follower_names & user2.follower_names).count

效果很好...但我希望可能有更快的方法。

最佳答案

集合为此更快。

require 'benchmark'
require 'set'
alphabet = ('a'..'z').to_a
user1_followers = 100.times.map{ alphabet.sample(3) }
user2_followers = 100.times.map{ alphabet.sample(3) }
user1_followers_set = user1_followers.to_set
user2_followers_set = user2_followers.to_set

n = 1000
Benchmark.bm(7) do |x|
x.report('arrays'){ n.times{ (user1_followers & user2_followers).size } }
x.report('set'){ n.times{ (user1_followers_set & user2_followers_set).size } }
end

输出:

              user     system      total        real
arrays 0.910000 0.000000 0.910000 ( 0.926098)
set 0.350000 0.000000 0.350000 ( 0.359571)

关于mysql - Ruby Array - 计算重叠的快速方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8725861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com