Skip to main content

Speeding Up 'For Loops'

Speeding Up 'For Loops'

The typical format for a ‘for loop’ to run through the list items in an array is as follows…

var myArray = [1, 2, 3, 5, 8, 13, 21, 34];
for (var i = 0;  i < myArray.length;  i++) {
    //myArray[i] becomes the variable run inside the loop
}

But you’ll notice that every time the loop is run, the length of the array is calculated…. Yet the number is always going to be the same… So we’re just wasting time processing for no reason… We could create a variable outside the ‘for loop’ and use that…. Or declare it when we set the loop up…. Like this:

for (var i = 0, ii = myArray.length;  i < ii;  i++) {
    //myArray[i] becomes the variable run inside the loop
}

This time, before the first semi-colon, we can declare more variables and spped the script up, whilst keeping it nice and neat at the same time…

Another little gem from Kevin Yank at Sitepoint

Main Category
  • Javascript
  •  
 
Jon Moore

Search form

Jon Moore

Tips 'n' Snips

 
  • Home
  • General
  • Drupal
    • Drupal 6
    • Drupal 7
    • Module Building
  • HTML & CSS
  • Javascript
  • jQuery
  • PHP
    • CodeIgniter
    • Handy Functions
    • MySQL
  • WordPress
  • About

BBC Technology News

  • Kashmir users kicked off WhatsApp
  • Heavy fine for Chinese firm over unlicensed game
  • Uber had 6,000 US sexual assault reports in two years
  • Electric eel lights up Christmas tree and other news
  • Rory Cellan-Jones: Reporting the news with Parkinson's
More

Sitepoint

  • The Real Future of Remote Work is Asynchronous
  • 7 Ways Developers Can Contribute to Climate Action
  • How to Divert Traffic Using IP2Location in a Next.js Website
  • 10 Zsh Tips & Tricks: Configuration, Customization & Usage
  • Building a Habit Tracker with Prisma, Chakra UI, and React
More

Heart Internet

  • Sponsor Neil Hunter’s amazing Antarctic expedition – for Diabetes UK
  • 15 web design books of 2019 that you should read
  • 12 podcasts for every creative person’s commute
  • Ten TED Talks every designer and web creative should watch before 2019 is over
  • The rise of the robots: Will AI take over graphic design?
More
 

Backend Coders

  • PHP
  • Handy PHP Functions
  • PHP MySQL

Frontend Coders

  • HTML & CSS
  • jQuery
  • Javascript

CMS/CMF Systems

  • Drupal
  • Drupal 6 Specific
  • Drupal 7 Specific
  • Drupal Module Building
  • WordPress

About

  • Home
  • About
 

© Jon Moore 2019

All stock images are from www.istockphoto.com