最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asp.net - Speed up a web service for auto complete and avoid too many method calls - Stack Overflow

programmeradmin3浏览0评论

So I've got my jquery autoplete 'working,' but its a little fidgety since I call the webservice method each time a keydown() fires so I get lots of methods hanging and sometimes to get the "auto" to work I have to type it out and backspace a bit because i'm assuming it got its return value a little slow. I've limited the query results to 8 to mininmize time. Is there anything i can do to make this a little snappier? This thing seems near useless if I don't get it a little more responsive.

javascript

$("#clientAutoNames").keydown(function () {
        $.ajax({
            type: "POST",
            url: "WebService.asmx/LoadData",
            data: "{'input':" + JSON.stringify($("#clientAutoNames").val()) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data.d != null) {
                    var serviceScript = data.d;
                }
                $("#autoNames").html(serviceScript);
                $('#clientAutoNames').autoplete({
                    minLength: 2,
                    source: autoNames,
                    delay: 100,
                    focus: function (event, ui) {
                        $('#project').val(ui.item.label);
                        return false;
                    },
                    select: function (event, ui) {
                        $('#clientAutoNames').val(ui.item.label);
                        $('#projectid').val(ui.item.value);
                        $('#project-description').html(ui.item.desc);
                        pkey = $('#project-id').val;
                        return false;
                    }
                })
            .data("autoplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                    .data("item.autoplete", item)
                    .append("<a>" + item.label + "<br>" + item.desc + "</a>")
                    .appendTo(ul);
            }
            }
        });
    });

WebService.asmx

<WebMethod()> _
Public Function LoadData(ByVal input As String) As String
    Dim result As String = "<script>var autoNames = ["
    Dim sqlOut As Data.SqlClient.SqlDataReader
    Dim connstring As String = *Datasource*

    Dim strSql As String = "SELECT TOP 2 * FROM v_Clients WHERE (SearchName Like '" + input + "%') ORDER BY SearchName"
    Dim cnn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(connstring)
    Dim cmd As Data.SqlClient.SqlCommand = New Data.SqlClient.SqlCommand(strSql, cnn)
    cnn.Open()

    sqlOut = cmd.ExecuteReader()
    Dim c As Integer = 0
    While sqlOut.Read()

        result = result + "{"
        result = result + "value: '" + sqlOut("ContactID").ToString() + "',"
        result = result + "label: '" + sqlOut("SearchName").ToString() + "',"
        'result = result + "desc: '" + title + " from " + pany + "',"
        result = result + "},"

    End While
    result = result + "];</script>"
    sqlOut.Close()
    cnn.Close()

    Return result
End Function

I'm sure I'm just going about this slightly wrong or not doing a better balance of calls or something.

Greatly appreciated!

So I've got my jquery autoplete 'working,' but its a little fidgety since I call the webservice method each time a keydown() fires so I get lots of methods hanging and sometimes to get the "auto" to work I have to type it out and backspace a bit because i'm assuming it got its return value a little slow. I've limited the query results to 8 to mininmize time. Is there anything i can do to make this a little snappier? This thing seems near useless if I don't get it a little more responsive.

javascript

$("#clientAutoNames").keydown(function () {
        $.ajax({
            type: "POST",
            url: "WebService.asmx/LoadData",
            data: "{'input':" + JSON.stringify($("#clientAutoNames").val()) + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data.d != null) {
                    var serviceScript = data.d;
                }
                $("#autoNames").html(serviceScript);
                $('#clientAutoNames').autoplete({
                    minLength: 2,
                    source: autoNames,
                    delay: 100,
                    focus: function (event, ui) {
                        $('#project').val(ui.item.label);
                        return false;
                    },
                    select: function (event, ui) {
                        $('#clientAutoNames').val(ui.item.label);
                        $('#projectid').val(ui.item.value);
                        $('#project-description').html(ui.item.desc);
                        pkey = $('#project-id').val;
                        return false;
                    }
                })
            .data("autoplete")._renderItem = function (ul, item) {
                return $("<li></li>")
                    .data("item.autoplete", item)
                    .append("<a>" + item.label + "<br>" + item.desc + "</a>")
                    .appendTo(ul);
            }
            }
        });
    });

WebService.asmx

<WebMethod()> _
Public Function LoadData(ByVal input As String) As String
    Dim result As String = "<script>var autoNames = ["
    Dim sqlOut As Data.SqlClient.SqlDataReader
    Dim connstring As String = *Datasource*

    Dim strSql As String = "SELECT TOP 2 * FROM v_Clients WHERE (SearchName Like '" + input + "%') ORDER BY SearchName"
    Dim cnn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(connstring)
    Dim cmd As Data.SqlClient.SqlCommand = New Data.SqlClient.SqlCommand(strSql, cnn)
    cnn.Open()

    sqlOut = cmd.ExecuteReader()
    Dim c As Integer = 0
    While sqlOut.Read()

        result = result + "{"
        result = result + "value: '" + sqlOut("ContactID").ToString() + "',"
        result = result + "label: '" + sqlOut("SearchName").ToString() + "',"
        'result = result + "desc: '" + title + " from " + pany + "',"
        result = result + "},"

    End While
    result = result + "];</script>"
    sqlOut.Close()
    cnn.Close()

    Return result
End Function

I'm sure I'm just going about this slightly wrong or not doing a better balance of calls or something.

Greatly appreciated!

Share Improve this question asked Jun 11, 2010 at 19:36 Jon PhenowJon Phenow 4,1445 gold badges28 silver badges30 bronze badges 3
  • Does the "delay: 100" mean 100ms? – Steven Sudit Commented Jun 11, 2010 at 19:49
  • yup, I don't think when I read the API I read it the way you did. For some reason I thought the delay was how long it would wait until the suggestions were even displayed - I figured that'd just make things slower for my end-user – Jon Phenow Commented Jun 11, 2010 at 19:55
  • Turns out I was right about how delay is used. I pulled this up with firebug and its still called pretty quick, I wonder if I should change this to ajax call to be called by a function so I have more control on when i get results so I can create that delay. – Jon Phenow Commented Jun 11, 2010 at 19:59
Add a ment  | 

5 Answers 5

Reset to default 8

First off, you MUST adjust your query. You're not using parameterized queries, so you're just begging for a SQL injection attack.

Again, you MUST fix that first!

Once you've done that, play with the "delay" value. I assume that's the amount of time it waits between keystokes before sending the query to the server? You want it to wait for your users to pause in their typing, and then send the request, to avoid overloading your server with extraneous calls.

You should also use a try..catch..finally and dispose of your connection when you're done with it.

By the way, if your query is performing poorly, try adding an index on that column. 'Like' statements are terrible if you don't have an index...

You should first consider caching the results that are ing back from the database before doing anything else. This will limit the amount of queries that you are executing against the database. If you are running these queries through a single web server, consider using the System.Web.Cache for caching the results.

Any other advice on how to optimize will depend on more information than you have provided -- i.e. are you running across a web farm, how many database servers do you have, what are your performance requirements, etc.

I would also remend you read the Wikipedia entry on SQL injection. I believe ASP.NET will prevent requests that include singe quotes by default, but you should still fix your code.

Some suggestions for "snappier"

Depending on the requirements, you might build in preventative measures on the client side against too many server calls and implied call latency. For example,

  • auto plete can only kick in after at least 3 characters have been typed; otherwise the results are too broad to matter;
  • the list should continually get smaller as the user types more, so cache the original list on the client-side and filter it as the user continues typing more chars. If the user backspaces past the original result set then grab a new one from the server and do the same with it.
  • employ a client-side timer to issue calls no sooner than 2 or 3 seconds apart. keydown would detect a change in the text box and when your timer fires it looks at that flag to determine if it should pull data again

Granted, some of these might not contribute to snappiness, but it depends on how you use them. For example, the timer delay doesn't logically contribute to speed but then again paring the alternative of the server being inundated with calls and responding slower, it might. Mileage always varies with this type of optimization and you often trade up server work for client speed.

You could use Data Caching on the Webservice & save some data on the server rather than going to the DB on subsequent calls.

If the data in v_Clients does not have too many records, you can just put the whole thing in the cache, and use LINQ to query it.

http://msdn.microsoft./en-us/library/system.web.httpcontext.cache.aspx

you want to avoid calling the server on each keystroke unless absolutely necessary..

is it querying a huge dataset? if not, you can cache the whole dataset in a local variable on page load.

if the dataset is huge, you can think of smart caching, i.e. caching data that is used most of the time and than get the less mon scenarios on demand.

also prevent autoplete on first few characters. i.e. require at least 4 to make the call.

you'll have to use your judgement here, but measure and observe as you tweak, to get a good idea of performance / data reliability etc..

发布评论

评论列表(0)

  1. 暂无评论