Opensturt and struct differences

Source: Internet
Author: User

1 openstruct and struct differences, opestruct you need to create, assign a value directly to the property, and the struct needs to define the attribute before assigning a value to the property. Choose which one to look at when you assign values to a property,

2 structs and Opensturt represent properties that are more closely related than hashes. But they do not have as an instance method of the class, a set of optional functions, if you need to provide a special method for the property, it is best to create a class

3 openstruct can be converted to an object using hash
H = {a:1, b:2}
o = openstruct.new (h)
O.A = 1
O.B = 2

4 structs can quickly define a class

Class MyClass < Struct.new (: A,:B,:C)
End

m = myclass.new
M.A = 1


The following code is the test opensturct and struct speed

Require ' benchmark '
Require ' ostruct '

REP = 100000

User = struct.new (: Name,: Age)

user = "User". Freeze
Age = 21
HASH = {: name = USER,: Age = Age}.freeze

BENCHMARK.BM do |x|
X.report ' openstruct slow ' do
Rep.times do |index|
Openstruct.new (: name = "User",: Age + 21)
End
End

X.report ' openstruct fast ' do
Rep.times do |index|
Openstruct.new (HASH)
End
End

X.report ' Struct slow ' do
Rep.times do |index|
User.new ("User", 21)
End
End

X.report ' Struct fast ' do
Rep.times do |index|
User.new (USER, age)
End
End
End

Opensturt and struct differences

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.