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()
200_success
145k22 gold badges190 silver badges478 bronze badges
asked May 5, 2014 at 20:54
\$\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()
answered May 5, 2014 at 22:10
\$\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.

answered May 5, 2014 at 22:18
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.