Skip to content

Faster Rails: Use exists instead of present? to check if a Record Exists #232

Open
@zoras

Description

@zoras

Prefer exists?instead of present? for checking record according to this blog post.

... exists?, is even more optimized, and it should be your first choice when checking the existence of a record. It uses the SELECT 1 ... LIMIT 1 approach, which is very fast.

Also, prefer any? and empty? when checking for the existence of an association record without any scope.

... any? and empty? will also produce a very optimized query that uses SELECT 1 FROM ... LIMIT 1 form, but any? will not hit the database again if the records are already loaded into memory.

This makes any? faster by one whole database call when the records are already loaded into memory:

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions