2
\$\begingroup\$

Is there a more efficient approach to this code?

// save associated tag
let saveTag question = 

    if question.Tag = null then
        ()
        else
            let tagCount = 
                query{
                    for row in db.Tags_Tags_Tags do
                    where (row.Tag = question.Tag)
                    select row
                    count
                } 

            if tagCount > 0 then
                ()
                else
                    let tagToSave = 
                        dbSchema.ServiceTypes.Tags_Tags_Tags(
                            Tag = question.Tag
                        )
                    insertRowIn db.Tags_Tags_Tags tagToSave
                    saveToDb()
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

You don't need the empty if branches. An if without an else automatically returns unit. So you can simplify it to:

let saveTag question = 

    if question.Tag <> null then
        let tagCount = 
            query{
                for row in db.Tags_Tags_Tags do
                where (row.Tag = question.Tag)
                select row
                count
            } 

        if tagCount = 0 then
            let tagToSave = 
                dbSchema.ServiceTypes.Tags_Tags_Tags(
                    Tag = question.Tag
                )
            insertRowIn db.Tags_Tags_Tags tagToSave
            saveToDb()
\$\endgroup\$
4
\$\begingroup\$

In addition to Daniel's answer, the select row in your tagCount query is redundant. You can simplify the query to:

    let tagCount = 
        query {
            for row in db.Tags_Tags_Tags do
            where (row.Tag = question.Tag)
            count
        } 

But you could further improve your query. In this case you don't actually need to know the exact count, you just need to know if there's at least one match or not.

let tagExists =
    query {
        for row in db.Tags_Tags_Tags do
        exists (row.Tag = question.Tag)
    }

if not tagExists then
    ...

This way the query can stop processing as soon as it finds a match, instead of continuing on until it has an exact count of how many matches. It's a bit more efficient that way when there's lots of data.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.