SOLVED - How to optimize my for loop? (2024)

ThisThing

Member

Mar 24, 2024

  • #1

I am using this loop:

GML:

var _val = 80;for (var i = 0; i < 30; i++) { var _xx = irandom_range(-_val, _val); var _yy = irandom_range(-_val, _val); dest_x = x + _xx; dest_y = y + _yy; // loop if target location is inside solid object while collision_circle(dest_x, dest_y, 32, o_solid, 1, 0) { _xx = irandom_range(-_val, _val); _yy = irandom_range(-_val, _val); dest_x = x + _xx; dest_y = y + _yy; }}

Desc: It is pretty much taken straight from the manual. What I am doing, or trying to do properly, is to get a y / x location that is not inside a solid object (dest_x and dest_y). I then have an 'entity' object move to that location.

Question: What would be a better approach than using the 'i < 30' that I am using? I mean, what if a location outside a solid has not been found within 30 steps? I could just increase the number of steps to check, but are there not a better way?

Any help is much appreciated.

Yal

🐧 *penguin noises*

GMC Elder

Mar 24, 2024

  • #2

The right answer here depends a bit on how the rest of your game works, for instance you could store a list of all valid positions and then pick one of those randomly, but it becomes impractical if things spawn/move a lot (and invalidates those positions each time).

Also since you only check at a range of up to 80 pixels away, if enough of these things spawn at roughly the same area there might be literally no valid positions left after a while. One idea to fix this would be to increase "val" by 10% each time you fail, eventually it'll grow big enough that your random position is free even if it means this object needs to spawn outside the room.

Another idea is to spawn the things at x, y and not check for collisions at all, but the objects has a collision event that moves them out of solid objects by XYZ distance each step (you could even give them a little bouncy animation or something to make it look like they bounce off the obstacles). Finding the direction to move is gonna be tricky if you don't wanna do collision checks everywhere, but a safe assumption if these objects are items you want to pick up would be something like, "pick the direction towards the player, add a random value between -25 and 25 degrees" - if they're stuck on spawn, they move in this direction until they're not.

RefresherTowel

Member

Mar 24, 2024

  • #3

GML:

var _dest_x, _dest_y, _max_loops = 1000, _val = 80;do { _dest_x = x + irandom_range(-_val, _val); _dest_y = y + irandom_range(-_val, _val); _max_loops--;}until (!collision_circle(_dest_x, _dest_y, 32, o_solid, 1, 0) || _max_loops <= 0);

That'll run either 1000 loops or until collision circle is free. You can tell which happened by checking the value of _max_loops. If it's 0 or less, it didn't find a place, otherwise _dest_x and _dest_y are free.

ThisThing

Member

Mar 24, 2024

  • #4

RefresherTowel said:

GML:

var _dest_x, _dest_y, _max_loops = 1000, _val = 80;do { _dest_x = x + irandom_range(-_val, _val); _dest_y = y + irandom_range(-_val, _val); _max_loops--;}until (!collision_circle(_dest_x, _dest_y, 32, o_solid, 1, 0) || _max_loops <= 0);

That'll run either 1000 loops or until collision circle is free. You can tell which happened by checking the value of _max_loops. If it's 0 or less, it didn't find a place, otherwise _dest_x and _dest_y are free.

Okay, I'll try this right away. What will happen, however, if a free space is not found after 1000 loops? Just in theory?

ThisThing

Member

Mar 24, 2024

  • #5

Yal said:

The right answer here depends a bit on how the rest of your game works, for instance you could store a list of all valid positions and then pick one of those randomly, but it becomes impractical if things spawn/move a lot (and invalidates those positions each time).

Also since you only check at a range of up to 80 pixels away, if enough of these things spawn at roughly the same area there might be literally no valid positions left after a while. One idea to fix this would be to increase "val" by 10% each time you fail, eventually it'll grow big enough that your random position is free even if it means this object needs to spawn outside the room.

Another idea is to spawn the things at x, y and not check for collisions at all, but the objects has a collision event that moves them out of solid objects by XYZ distance each step (you could even give them a little bouncy animation or something to make it look like they bounce off the obstacles). Finding the direction to move is gonna be tricky if you don't wanna do collision checks everywhere, but a safe assumption if these objects are items you want to pick up would be something like, "pick the direction towards the player, add a random value between -25 and 25 degrees" - if they're stuck on spawn, they move in this direction until they're not.

Okay, I will explain further:
It is a top-down (like GTA2) and this code is for the enemy. When the enemy reaches dest_x / dest_y it count down to when to change location. Then I run this code to find an area around the enemy itself to go to. I use mp_potential so I want to avoid any dest_x/dest_y inside a solid object.

Solid object will not be able to spawn during gameplay (and are not planned to do so). This code is more to find a free destination, and not so much spawning things.

However, I am interested in the way you increase the radius by 10% each fail. That is a cool little trick.

RefresherTowel

Member

Mar 24, 2024

  • #6

ThisThing said:

Okay, I'll try this right away. What will happen, however, if a free space is not found after 1000 loops? Just in theory?

Using that immediate code, nothing will happen beyond the loop ending. However, if you are going to then go on and try to create an instance using _dest_x and _dest_y as that instances starting position, then the instance will be created on top of some obstacle somewhere (because there was no valid free space found). You would use the value of _max_loops to determine if you can create an instance or not. If _max_loops is less than or equal to 0 then you did not find a valid space, and therefore you should not try to create the instance (or, at least, you should be aware that if you do create an instance it will be colliding with something). However, if _max_loops is any positive number, then you know the loop ended because there was a free space found, instead of _max_loops hitting 0, which means that _dest_x and _dest_y are holding a valid position that doesn't have a collision registering and you can create an instance there knowing it won't be colliding with any o_solid instances.

That's all assuming the point is to create an instance in a free spot. But no matter the actual end goal, you know what your two potential outcomes are. _max_loops > 0, no collisions were found, else if _max_loops <= 0 no valid space could be found within the number of loops it tried.

ThisThing

Member

Mar 25, 2024

  • #7

RefresherTowel said:

Using that immediate code, nothing will happen beyond the loop ending. However, if you are going to then go on and try to create an instance using _dest_x and _dest_y as that instances starting position, then the instance will be created on top of some obstacle somewhere (because there was no valid free space found). You would use the value of _max_loops to determine if you can create an instance or not. If _max_loops is less than or equal to 0 then you did not find a valid space, and therefore you should not try to create the instance (or, at least, you should be aware that if you do create an instance it will be colliding with something). However, if _max_loops is any positive number, then you know the loop ended because there was a free space found, instead of _max_loops hitting 0, which means that _dest_x and _dest_y are holding a valid position that doesn't have a collision registering and you can create an instance there knowing it won't be colliding with any o_solid instances.

That's all assuming the point is to create an instance in a free spot. But no matter the actual end goal, you know what your two potential outcomes are. _max_loops > 0, no collisions were found, else if _max_loops <= 0 no valid space could be found within the number of loops it tried.

Ah, that makes total sense! What a good idea.
I am just finding a free spot to move to here, but the idea to use _max_loops that way is so simple yet smart.
Thanks a lot.

You must log in or register to reply here.

SOLVED - How to optimize my for loop? (2024)

FAQs

SOLVED - How to optimize my for loop? ›

To optimize for loops in C, consider techniques such as loop unrolling, reducing iterations, reusing values, loop invariant code motion, using cache-friendly data structures, and parallelization. Balance these optimizations with code readability and maintainability, and measure performance to ensure improvement.

How to improve code performance in a loop? ›

To optimize for loops in C, consider techniques such as loop unrolling, reducing iterations, reusing values, loop invariant code motion, using cache-friendly data structures, and parallelization. Balance these optimizations with code readability and maintainability, and measure performance to ensure improvement.

How to optimize for loop in JavaScript? ›

To optimize a for loop in JavaScript, you can use the following techniques:
  1. Use the let keyword instead of the var keyword. ...
  2. Move expensive computations or operations outside of the loop.
  3. Use the continue statement to skip unnecessary iterations.
  4. Use the break statement to exit the loop early.
Dec 1, 2022

How to optimize two for loops in Java? ›

Here are some strategies you can apply:
  1. Reduce the Iteration Range: Ensure that the loop limits are set to the minimum required range. ...
  2. Loop Interchange: ...
  3. Minimize Work Inside Loops: ...
  4. Use Local Variables: ...
  5. Loop Unrolling: ...
  6. Avoid Unnecessary Computations: ...
  7. Use Primitives Instead of Objects: ...
  8. Caching Values:
Dec 28, 2022

What are the 3 parts needed for loops to run successfully? ›

A For loop consists of three parts:
  • Initialization: It is the beginning of the loop.
  • Condition: It is also called end-value. The condition is to be tested each time the loop iterates or is performed.
  • Increment / Decrement: It's a value-added or subtracted from the control variable at every loop turn.
Jan 11, 2021

How to optimise a for loop? ›

Minimize Loop Iterations:

One of the fundamental principles of loop optimization is to minimize the number of iterations. The fewer times the loop runs, the better the performance. Therefore, it's important to carefully consider the conditions and logic within the loop to ensure that unnecessary iterations are avoided.

How to make for loop fast? ›

  1. 2.4x speedup using List Comprehension.
  2. 1.6x speedup by moving list length calculation outside the for loop.
  3. 498x speedup using sets for scenarios you'd otherwise use nested for loops for comparisons.
  4. 1.9x speedup.
  5. 1.3x speedup.
  6. 1.9x speedup by avoiding pointless checks.
Dec 31, 2023

What is the most efficient loop in JavaScript? ›

forEach() loop

It performs highly efficient tasks where functional code is required. It is basically a callback function dependent highly on the operation performed inside.

How to increase performance in JavaScript? ›

JavaScript Optimization Tips To Improve Performance in 2024
  1. Order in which elements are loaded. ...
  2. Minify JavaScript code for smaller file sizes. ...
  3. Optimize Javascript with minification. ...
  4. Asynchronous loading of JavaScript: Defer and Async tags. ...
  5. Exclude unused components of . ...
  6. Use the HTTP/2 protocol.

How to slow down a loop in JavaScript? ›

How to add a delay in a JavaScript loop?
  1. for (let i=0; i<10; i++) { task(i); } function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i); }
  2. let i = 0; while (i < 10) { task(i); i++; } function task(i) { setTimeout(function() { // Add tasks to do }, 2000 * i); }
May 31, 2024

How to increase the performance of for loop in Java? ›

Here are some tips for optimizing loops in Java:
  1. Use the enhanced for-loop (for-each loop) when possible for improved readability and performance.
  2. Minimize method calls and calculations inside loops by moving them outside the loop.
  3. Avoid creating objects within loops, as it can increase garbage collection overhead.
Mar 24, 2023

How do you reduce the time complexity of two for loops? ›

Memoization: Memoization can be used to reduce O(N²) to O(N) for recursive algorithms by avoiding redundant computations. For example, in the longest common subsequence problem, if we memoize the values of the subsequence that we have already calculated, we can reduce the time complexity from O(2^n) to O(N^2).

How to reduce time complexity? ›

How can you reduce the time and space complexity of your algorithm design?
  1. Choose the right data structure.
  2. Use divide and conquer.
  3. Apply dynamic programming.
  4. Optimize loops and conditions. Be the first to add your personal experience.
  5. Test and debug your code.
  6. Here's what else to consider.
Sep 13, 2023

Which situation would work best with a for loop? ›

For Loop: A for loop is an iteration method that is best used when you know the number of iterations ahead of time. It's always followed by the initialization, expression and increment statements.

What is the most common problem with the use of loops in programming? ›

Loops can easily go wrong with the most common problems being: Loops that never start. Loops that never finish. Loops that repeat the wrong number of times.

What is the maximum number of conditions allowed in a for loop? ›

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.

How do you optimize code performance? ›

There are several techniques you can use to optimize your code. You can start by using the right data types, simplifying your code, avoiding unnecessary computations, caching frequently used data, avoiding unnecessary I/O, and implementing the most efficient algorithms.

How to improve for-loop performance in Python? ›

  1. Don't use loops at all.
  2. Use enumerate.
  3. Use zip.
  4. Think lazy!
  5. Use itertools more! itertools.islice() pairwise() takewhile()
  6. Use NumPy.

How do I make my loop run slower? ›

Just put the timeout in the for-loop, and the loop is less fast: When we run the code with setTimeout, the following happens: nothing happens for 1 second; then all the logs come up in a flash.

How do I make my code run faster? ›

In general, though, there are a few basic principles you can follow to optimize your code:
  1. Use the right data types. Data types are the key to optimizing code performance. ...
  2. Keep your code as simple as possible. ...
  3. Avoid unnecessary computations. ...
  4. Cache frequently used data. ...
  5. Avoid unnecessary I/O. ...
  6. Use the most efficient algorithms.
Sep 21, 2022

Top Articles
Election latest: Tories to collapse in worst result ever, exit poll projects
Buy lawn mower? - Coolblue
Steve Bannon Issues Warning To Donald Trump
Lux Nails Columbia Mo
Kool Online Offender Lookup
Sessional Dates U Of T
Lifestyle | Stewartstown-Fawn Grove Daily Voice
Duralast Battery H6-Dl Group Size 48 680 Cca
Chs.mywork
‘Sound of Freedom’ Is Now Streaming: Here’s Where to Stream the Controversial Crime Thriller Online for Free
Uta Frontrunner Twitter
Post-Tribune Obits
6Th Gen Camaro Forums
Mobile Maher Terminal
Martimelons
Math Playground Protractor
Craigslis Nc
Tuition Fee Compensation
Baca's Funeral Chapels & Sunset Crematory Las Cruces Obituaries
Liquor World Sharon Ma
Tamilyogi. Vip
Magicseaweed Capitola
Regal Stone Pokemon Gaia
Kyle Gibson Stats Vs Blue Jays 5 Games | StatMuse
Exploring IranProud: A Gateway to Iranian Entertainment
WhirlyBall: next-level bumper cars
Movierulz.com Kannada 2024 Download: Your Ultimate Guide
Craigslist Apts Near Me
5128 Se Bybee Blvd
Live Stream Portal
Why Do Dogs Wag Their Tails? Scientists Examine the Endearing Behavior
Metro By T Mobile Sign In
Green Warriors of Norway: “Salvage the 67 tonnes mercury bomb now” | Norges Miljøvernforbund
Parishes Online Bulletins
Southeast Ia Craigslist
Zuercher Portal Inmates Kershaw County
ACMG - American College of Medical Genetics and Genomics on LinkedIn: #medicalgenetics #genomics
9 best hotels in Atlanta to check out in 2023 - The Points Guy
Dvax Message Board
Liv Morgan Wedgie
Rs3 Bis Perks
Intriguing Facts About Tom Jones Star Hannah Waddingham
Sep Latest Version
Boostmaster Lin Yupoo
Viduthalai Movierulz
Uncg Directions
Six Broadway Wiki
El Pulpo Auto Parts Houston
Dtm Urban Dictionary
Markella Magliola Obituary
Remembering the life of Jeff Hewson.
Vimeo Downloader - Download Vimeo Videos Online - VEED.IO
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 6259

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.