设为首页收藏本站|繁體中文

Project1

 找回密码
 注册会员
搜索
查看: 2680|回复: 4
打印 上一主题 下一主题

[讨论] 【效率测试】Ruby中include方法的效率问题

[复制链接]

Lv4.逐梦者 (版主)

梦石
0
星屑
9497
在线时间
5073 小时
注册时间
2013-6-21
帖子
3580

开拓者贵宾剧作品鉴家

1
发表于 2015-1-28 14:24:57 | 显示全部楼层
我的测试结果:

因为机子太慢我改成5000000了TAT

啥?为啥不一样?因为我改了源码。
RUBY 代码复制
  1. class Test
  2.   def self.test(string,&block)
  3.     time = Time.new
  4.     block.call
  5.     puts string,Time.new-time
  6.   end
  7. end
  8.  
  9. class Point
  10.   attr_accessor :x, :y
  11.   def initialize(x, y)
  12.     @x = x
  13.     @y = y
  14.   end
  15.   def ==(point)
  16.     return @x==point.x && @y==point.y
  17.   end
  18. end
  19.  
  20. class Array
  21.   def point_include?(point_arr)
  22.     self.each do |point|
  23.       return true if point[0] == point_arr[0] && point[1] == point_arr[1]
  24.     end
  25.     return false
  26.   end
  27. end
  28.  
  29.  
  30. point1 = Array.new
  31. point2 = Array.new
  32. max = 5000000
  33.  
  34. Test.test("Push Class Point") { max.times { |i| point1.push Point.new(i,i) } }
  35.  
  36. Test.test("Push Class Array") { max.times { |i| point2.push [i,i] } }
  37.  
  38. Test.test("Include Class Point") { point1.include?(Point.new(max,0)) } # 取最坏情况
  39.  
  40. Test.test("Include Class Array") { point2.point_include?([max,0]) }

总觉得Array#==方法太不自然了。

点评

Array也是一个对象  发表于 2015-1-28 15:44
话说Ruby真是想什么就有什么,我只是试着clone一下就成功了  发表于 2015-1-28 15:40
我用Array=Array.clone在类的内部创建了一个副本,这样就不会影响到外面了~  发表于 2015-1-28 15:38
+1,这样改来,还是Array快一点。= =不过还要袭击内部类,真是各种蛋疼。。。  发表于 2015-1-28 14:41

评分

参与人数 2星屑 +190 收起 理由
恐惧剑刃 + 150 认可答案
寒冷魔王 + 40 帅气

查看全部评分

回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

拿上你的纸笔,建造一个属于你的梦想世界,加入吧。
 注册会员
找回密码

站长信箱:[email protected]|手机版|小黑屋|无图版|Project1游戏制作

GMT+8, 2024-5-17 06:20

Powered by Discuz! X3.1

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表