Optimal method for iterating through this array efficiently using Javascript in Chrome version 36

My array is quite large, resembling the following:

var counts = ["gfdg 34243", "jhfj 543554", ....] // With a length of 55268 elements

This is my current loop:

var replace = "";
var scored = 0;
var qgram = "";
var score1 = 0;
var len = counts.length;

function score(pplaintext1) {
    qgram = pplaintext1;
    for (var x = 0; x < qgram.length; x++) {
        for (var a = 0, len = counts.length; a < len; a++) {
            if (qgram.substring(x, x + 4) === counts[a].substring(0, 4)) {
                replace = parseInt(counts[a].replace(/[^1-9]/g, ""));
                scored += Math.log(replace / len) * Math.LOG10E;
            } else {
                scored += Math.log(1 / len) * Math.LOG10E;
            }
        }
    }
    score1 = scored;
    scored = 0;
} // This function needs to be called roughly 1000 times

I need to iterate through this array multiple times and my code is slowing down. I'm wondering what would be the most efficient way to iterate through this array to maximize time savings.

Answer №1

Your list of unique strings and values in the `counts` array can be optimized by using an object instead, where the unique strings act as keys:

var counts = { gfdg: 34243, jhfj: 543554, ... };

This change will significantly enhance performance by eliminating the need for an inner loop with a time complexity of O(n) and replacing it with constant-time lookup using object keys (O(1)).

In addition, it's recommended to avoid divisions like `log(1 / n) = -log(n)` and move loop invariants outside the loops. The expression `log(1/len) * Math.LOG10E` adds a constant value in each pass except in the first `if` statement branch, where you must also consider `Math.log(replace)` which means adding it in logarithmic calculations.

Furthermore, try not to rely on state variables from the outer scope for scoring purposes. You can refactor your scoring algorithm like this:

var len = Object.keys(counts).length;

function score(text) {
    var result = 0;
    var factor = -Math.log(len) * Math.LOG10E;

    for (var x = 0, n = text.length - 4; x < n; ++x) {
        var qgram = text.substring(x, x + 4);
        var replace = counts[qgram];
        if (replace) {
            result += Math.log(replace) + factor;
        } else {
            result += len * factor;  // once for each ngram
        }
    }
    return result;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The reactivity of Vuex mutation mutations may become compromised

state.js: export default () => ({ stepBarItems: [ { title: 'Introductory Details', active: false, current: false }, { title: 'Personal Information', active: false, current: false ...

Ways to prompt for user input using JavaScript

How can I collect user input using JavaScript for a website that saves the input into a text file? Below is the code I am currently using: <button type="button" onclick="storeEmail()">Enter Email</button> <script> ...

jQuery: Modifying tags is a one-time deal

I am trying to create a feature where a <p> tag becomes editable when clicked. However, I am encountering an issue - it can only be edited once. Upon a second click, an error message appears in the console. You can view the fiddle demonstrating this ...

The utilization of conditional expression necessitates the inclusion of all three expressions at the conclusion

<div *ngFor="let f of layout?.photoframes; let i = index" [attr.data-index]="i"> <input type="number" [(ngModel)]="f.x" [style.border-color]="(selectedObject===f) ? 'red'" /> </div> An error is triggered by the conditional ...

Building a responsive image gallery modal using AJAX in Laravel platform

How can I fix the issue of the modal content briefly appearing when I load my page? I am trying to create an image gallery where a modal opens when an image is clicked. Here is the code in my view.blade.php: <script> $(".li-img").click(function ( ...

Divide a single line in a Textarea into an array to be saved in MongoDB

Looking to utilize multiple data inputs by separating a line as an array string from the textarea in the backend of my NodeJS web application, in order to save them as new data in the collection: {"_id":"someid","Name":"T ...

Implementing a feature that loads older posts on a webpage as users scroll down

Spent hours trying to get my site to automatically load older posts on scroll down with no luck. Any assistance is greatly appreciated :) After researching, [this tutorial][1] seemed like the best solution so I followed it step by step and integrated ever ...

Error importing reach-router in Gatsbyjs causing website to break

While working on my Gatsby project, I decided to incorporate the React Cookie Consent package. However, upon installation and implementation attempt, my website crashed, displaying this error message: warn ./.cache/root.js Attempted import error: &a ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

Error encountered while attempting to upload a file using ajax

I'm having trouble uploading an image to my backend. Along with the image, I need to send three things - a file (a URL) and a title. However, every time I try to do this, I receive a "400 Bad Request" error. In the network tab, I can see a response si ...

Apply a watermark specifically to fancybox for images in galleries, excluding non-gallery items

I recently encountered an issue with a FancyBox image gallery on my webpage. I wanted to add a watermark to the gallery items, so I followed an example from the FancyBox page at http://jsfiddle.net/w5gQS/. beforeShow: function () { $('<div class=" ...

Encountering a peculiar error while attempting to install firebase-tools

Currently in the process of deploying my application on Firebase by following a tutorial. I encountered an issue after executing the command npm install -g firebase-tools: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" d ...

What is the best method for transforming CakePHP JSON into a format compatible with JS JIT SpaceTree?

I am currently utilizing CakePHP to execute a query on my database table 'Task', which consists of columns like project_id, id, parent_id, title, and description. The code in my controller that handles the query looks like this: $query= $this-&g ...

Ways to circumvent ng switch and create a component based on type

In my current code, I have an array called resourceTypes and I am using ngSwitch to create different components/directives based on the TypeName. However, I find this approach cumbersome as I have to update the code every time I add a new resource editor. ...

A guide on shading specific faces based on their normal vectors' alignment with the camera's view

https://i.sstatic.net/FG4hp.png I'm currently working on a shader that requires darkening the faces with normals perpendicular to the camera (dot product is 0). How can I calculate this dot product and make sure it works correctly? uniform float tim ...

What is the best way to employ a Node.js server for uninterrupted delivery of array updates to localhost?

My current approach involves creating an empty array, extracting the value associated with the first name key from a separate object, sending it to localhost through a Node.js server, iterating back to access new data from another object and adding it to t ...

Tips for regularly retrieving information from a psql table

I have a scenario where I am retrieving data from a psql table and converting it into a JSON array to be used for displaying a time series chart using JavaScript. The data that is passed needs to be in the form of an array. Since the data in the table get ...

Dynamic Variable Typing in TypeScript: Adjusting variable types on the fly

I am working with 2 variables named locals and visitants. These variables can either be of type PlayerDto or TeamDto, which will be determined by a third variable called competitor_type. If competitor_type is player, then I need to assign a list of Players ...

Troubleshooting issue with jquery.i18n.properties functionality

I am encountering an issue with implementing jQuery internationalization. I have included the files jquery.i18n.properties.js, jquery.i18n.properties-min.js, and jquery-min.js in my resources folder. In my jsp, I have added the following code: <script ...

Tips for transforming a few Nuxt snippets into Vue components

What is the best approach to transform this Nuxt script into a Vue-compatible one? <script> export default { components: { FeaturedProduct }, async asyncData({ axios }) { try { let response = await axios.get( 'http:// ...