Skip to content

Instantly share code, notes, and snippets.

@kieetnvt
Last active April 10, 2019 07:40
Show Gist options
  • Save kieetnvt/a1d54053a41ba09c99199c95a449e5c5 to your computer and use it in GitHub Desktop.
Save kieetnvt/a1d54053a41ba09c99199c95a449e5c5 to your computer and use it in GitHub Desktop.
Ruby optimization with Magic Comment

Trong việc phát triển phần mềm, muốn optimization đơn giản là làm được việc này: Find the way to do less!

Ruby thì chậm có tiếng rồi, thủ phạm chính đó là garbage collector của ruby.

Chúng ta có thể optimization ruby bằng cách tạo ít rác rưởi khi chúng ta code ruby.

String trong ruby thì mutable (thay đổi), sinh ra nhiều object rác.

Ví dụ: string = ""; string << "test" nó đã tạo 2 object string là "", và "test". (rác)

Ví dụ nữa: HASH = {"test": 123} => mỗi lần gọi HASH["test"] là 1 lần tạo 1 new object string "test". (rác)

Cách sửa: dùng freeze. Ruby support freeze để minimize allocation.

HASH["test".freeze] => fix được vụ rác nhưng nếu nhìn code (nhiều chỗ sử dụng như vậy) => khá khó chịu, code format xấu.

Cách sửa thứ 2: dùng Magic comment

Từ bản ruby 2.3 trở, nó support cho ta thêm comment # frozen_string_literal: true vào đầu file code rb, sẽ giúp chúng ta tự động chuyển All String thành immutable , không sinh thêm object rác.

# frozen_string_literal: true

HASH = {
  "test": 123
}

def getmike
  HASH["test"]
end

frozen_string_literal reduces the generated garbage by ~100MB or ~20%! Free performance by adding a one line comment.

Gem authors: add # frozen_string_literal: true to the top of all Ruby files in a gem. It gives a free performance improvement to all your users as long as you don't use String mutation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment