Blog

For vs foreach: the performance difference will shock you

I recently started looking at performance optimization applicable in Unity. Doing Google searches showed out-of-date tests (much like this could be if you are reading in the far future).

I’m specifically trying to determine which type of loop (For Vs. ForEach) is the most efficient to use as 1) referencing GameObjects and 2) modifying a value.

For these tests I’m using Unity 2020.3.19f1 LTS on Windows 10 with an i9-10850 CPU with 16GB RAM. For updating values, the GameObject position was changed. I ran the test seven times and used the average to come to a conclusion. This is more as a reference rather than the “be all and end all” of which case suits your best. Basically, do your own tests to see how each case would suit your own needs.

Without further ado, here is are my test results iterating an array of 100,000 GameObjects:

Results

Editor

IL2CPP EditorRead ValueSet Value
ForForEachForForEach
0.0033917430.0036640170.067594050.04567719
0.0034174920.0035285950.063674450.04667139
0.003467560.0035200120.066828730.05114985
0.0033812520.003345490.062442780.04349947
0.0034904480.0034618380.060833450.04655266
0.0034084320.0035433770.063357350.04396629
0.0035672190.0035228730.062111380.04444933
Editor For v ForEach Times in Seconds
Average0.0034463065710.0035123145710.063834598570.04599516857
Difference0.000066008-0.000066008-0.017839430.01783943
Editor For v ForEach Time differences in Seconds

Player Build

IL2CPP PlayerRead ValueSet Value
ForForEachForForEach
0.00063562390.00054788590.043213840.0290904
0.00063371660.00054359440.041841030.02432728
0.00062608720.00066947940.03976250.02416563
0.00062561040.00052881240.037984850.02457619
0.00064945220.00054883960.043627740.02631426
0.00062751770.00053358080.038517480.02418947
0.00063562390.00055551530.038239240.02412081
Player For v ForEach Times in Seconds
Average0.00063337598570.00056110111430.040455240.02525486286
Difference-0.000072274871430.00007227487143-0.015200377140.01520037714
Player For v ForEach Time differences in Seconds

Conclusions

First off, Unity Editor has a lot of overhead and is going to be always much slower than a build. Testing in Unity Editor will help determine if there are easy performance gains. When you want to get more realistic values you need the Player build used by players.

Comparing Timings between the Editor and Player build when reading elements in an array

Comparing the Editor to the Player build, and reading values from an array timings move from the 100ths into the 1000ths of a second. Setting values is much slower than reading values measured in 10ths. Modifying elements in a list has a performance cost, so don’t update elements needlessly (much like you shouldn’t in any kind of game loop, i.e. Unity’s Update()).

Reading elements in an array

Does it significantly matter if you are using a For or ForEach loop when reading elements in an array? We are talking 10,000ths of a second. Not a significant difference between the two. If you want the fastest iteration possible then ForEach wins when reading elements in an array.

Comparing Timings between the Editor and Player build when writing elements in an array

Modifying a GameObject value has its performance cost (probably more due to using the position Vector3 array which is a struct) and the difference is 2/100ths of a second, and significantly more costly than just reading values.

Writing elements in an array

ForEach is 15/100th faster than For. This difference is not going enough to worry about on its own but ForEach is faster and the best choice for getting as much performance as you can.

Other considerations

A last-minute thought, quite literally, any garbage collection from using a For or ForEach. Several years back ForEach generated garbage, then an update improved its performance. This experiment has not taken this into consideration and could make a considerable difference in how much Garbage is generated and thus make Garbage collection run more frequently, slowing performance and increasing frame hitches.

Testing on a variety of target machines could impact performance differently.

Using Mono scripting backend could impact performance differently.

TL;DR: ForEach was faster than For in this experiment. That alone should not influence any decision-making process.

UPDATE

Garbage collection was skewing the results. The first time you access the .transform for a GameObject Unity generates garbage.

I got around this by just doing an initial iteration before testing the times. From some initial testing ‘For’ won 4 out of 7 times in the 1/100th’s of seconds.

Based on this there is not much potential for performance gains. It’s best to choose for or foreach based on the needs of the project.

This garbage generation on first time accessing the transform may be worth noting for anyone who pools gameobjects.

In Development for PC: A-Spec First Assault

Digitum Software is pleased to announce a new tactical space simulator combat with fast and manoeuvrable corvettes to hulking warships armed with sophisticated yet traditional style weaponry known to modern military.

Experience first-person tactical space combat in A-Spec First Assault. Fly corvette class warships, customize your load-outs, and do battle against opposing forces where ship positioning matters.

Keep your enemy against your strongest side while you attack their weakest.
All warships use a quadrant damage model covering the front, right, rear, left sides. Positioning your ship is just as important to protect yourself as it is in attacking your target’s weak sides.

Familiar present-day weaponry
The majority of weaponry available will be familiar to present-day and mountable on turrets with limited firing arcs.

Prestige
Prestige Points are the main currency used to purchase new ships, weapons, and modules upgrades. Earn Prestige by completing mission objectives, taking down opponents, and avoiding damage to your ship’s hull.

Warship Customization
Customize your ship’s weaponry with a range of projectile and missile turrets. Turrets slots have a maximum supported size and fitting the biggest guns in each slot is not an option.

Enhance the abilities of your warship by fitting modules. Modules will have an impact on offensive and defensive ship systems and crucial for gaining an advantage during a fight.

Subscribe and Add to Wishlist to stay up-to-date and not miss out on development news and opportunities to play preview builds for A-Spec First Assault

Absolute territory updated to 2.2.0

2.2.0 Release (20210912)
Overview – Early enemy fighter weapons feel less overwhelming due to the fast firing rate

Gameplay

  • Amend – Track IR anchor point made same as VR
  • Amend – There are now two versions of the laser bolt cannon (Rapid Firing and Standard)
  • Amend – Vomitoria and Drosophilia now use slower firing laser bolt cannon
  • Amend – Updated weapon lore entries for the laser bolt cannon variants
  • Amend – Updated the 21 Absolute Territory missions to include the new standard laser bolt cannon. Added briefing text highlighting when new ships are made available. Added briefing text to make known about experimental laser weapon being available in mission 20

Simulator Modes

  • Amend – Wave and Gauntlet to include the new standard laser bolt cannon

Campaign Menu

  • Amend – Removed Tutorials as a campaign item selection (they are still available under Simulator menu). They no longer have skip dialogue, since all tutorials are available and there was no need to skip


2.0.1 Release (20210820)

Overview – Tunnelling can be disabled in options and an unsupported TrackIR implementation.

Visual

  • Added – Auto Exposure and Ambient Occlusion Postprocessing Effects
  • Amend – Gameplay scene lighting adjusted to use the Skybox instead of constant color.

Gameplay

  • Added – Toggle Tunnel Vision when using VR (Options > Game > VR Tunnelling
  • Added – An experimental and there not officially supported (I reserve the right to pull this feature at any time) Track IR implementation

VR

  • Amend – Press CTRL-F12 to recenter the VR headset in the main menu and in flight

An important developed note on the current Track IR implementation
As I don’t own any Track IR hardware I cannot reasonably test this myself and has been classed as experimental and officially unsupported. If you enable Track IR the experience may be sub-par or entirely broken. I will do my best to work with any Track IR users willing to be guinea pigs and provide relevant feedback towards improving the implementation. That is no guarantee that Track IR will become an official feature in the game and I reserve the right to abandon any further development on it.

Enabling Track IR
The command-line argument “-trackir” will be needed, I recommend you create a shortcut to the Standard game exe on your desktop and add the argument in the target box as exampled below.

Flying your Starfighter in Absolute Territory

Absolute Territory is a futuristic single-player mission-based space dogfighting with the familiar feeling of good space sims. Fly 21 missions with a variety of search & destroy, assault, patrol, escort, and scan objectives. Choose from several space superiority fighters, customize loadout from over a dozen weapons, manage power settings, and use directional thrusters like an elite pilot.

Ship and Weapon Selection

Outfit your chosen fighter in the Weapon Selection Screen

Chose your ship type from fast-moving glass cannons to slow hard-hitting tanks. Outfit your chosen ship with a variety of deadly weapons. Make sure you chose both ship and weapons wisely to enable the completion of your mission objectives.

Dogfighting with arcade-sim mechanics

Dogfighting against enemy stafighters

Engage in gripping dogfights with Newtonian physics. Arcade forces are used for an arcade-sim experience, allowing for responsive controls to pull off hair-raising maneuvers making yourself a harder target for enemies. AN RCS computer will compensation for all directional changes, turn too hard and you will but yourself into a slide, or worse find yourself a sitting duck while your ship adjusts speed. Fight against a variety of enemy ship types from light to heavy fighters, transports, and large warships.

Absolute Territory is not pure arcade or pure sim. Its arcade-sim.

Power management

Assaulting an enemy destroyer

Distribute power across engines, shields, and guns for an advantage over your opponent or get yourself out of sticky situations. Power to engines gives faster acceleration and increased top speed, for shields faster recharge rate and overcharging, and guns for faster recharge rate for longer sustained firing of heavier weapons.

Advanced flight mechanics

Picking off turrets using the slide mechanic

Engage slide, match speed, and directional thruster mechanics to keep your target in your gun sights. Warships and transports are not defenseless and come armed with flak turrets. Use component targeting and de-teeth these ships of their turrets. Then move in for the kill.

VR and Standard mode

Fully modelled cockpits to look around in VR

The recent 2.0 update added VR mode. Use this to your advantage for improved situational awareness in the cockpit. Identify the biggest threats with a glance before turning to engage.

Play Absolute Territory today

Better, faster and in VR!

The latest title update brings VR, a host of visual enhancements, and much more.

Greetings Pilots!

Allow me to introduce you to this huge title update bringing all-new VR mode! For those without VR headsets, there is a host of visual improvements and upgrades to pleasure your eyes.

To VR or not to VR?That is your choice. Make it a good one 🙂

VR provides a first-person experience piloting every starfighter available to fly. Each fighter has a 3D modeled cockpit to look around for improved situational awareness.

Warp to new horizonsTo keep you firmly seated in your cockpit, warp speed has been invented for transitioning to new areas during multi-staged missions faster than the speed of light.

Visual Enhancements

  • A range of visual enhancements brings increased fidelity to the original graphics along with:
  • Increase fighter texture quality for all Endophora fighters.
  • Lighting improvements for explosion effects.
  • 16 new skyboxes (updated in campaign, tutorial, waves, and gauntlet modes) along with their own unique lighting

New Graphics OptionsPCs have always been synonymous with configurability. 2.0 brings a wide range of video options to configure to either increase performance or increase visual quality.

The Enhanced Graphics option brings greater flexibility for increasing performance at the cost of visual quality or increasing visual quality at the cost of performance. Or you can just keep it disabled and use the default settings for the chosen Overall Quality setting.

User Accessibility

  • You can disable all camera shakes if you suffer from motion sickness.
  • Field of view provided in Standard mode,

Simulator Modes

  • Longevity brought to Waves and Gauntlet with ship selection. Test your flying skills with all 6 Imperial fighters along with full weapon load-outs.
  • Gauntlet now provides shield recharging and ammo restock at the end of each mission.

Wheres the rest?Check out the latest patch notes for the full list of new features, improvements, and bugfixes.

Weeklong sale and upcoming features and fixes

Absolute Territory started the Chinese New Year celebrations with a sale and what better way to end the celebration with a 40% off weeklong sale! Read on if you would like to know more about the upcoming VR update and other features and fixes?

Weeklong Sale

Save 40% off Absolute Territory on SteamHumble StoreMicrosoft StoreItch.io, or Gamejolt.

Upcoming Updates

Plans are in progress for the next major update for Absolute Territory. Along with performance improvements and video options to improve performance on potato PC’s, there will be an optional VR mode added to Absolute Territory, a new alien cockpit, campaign story changes, and improved missile-seeking behavior. Read on to learn more.

Optional VR Mode

For the last couple of months, I have been putting my efforts into adding optional VR support. It turned out to be more challenging than expected, but it’s coming along nicely. You will get to fly your space fighter while looking around a fully modeled cockpit in VR for all flyable fighters.

A new alien cockpit model has been added for all the flyable Endophora (Enemy) fighters if you choose to fly them in a custom mission. Basically, all space fighters now have a 3D modeled cockpit to look around in both VR and non-VR.

Alien Cockpit for Endophora fighters

For improved readability and comfort in VR, all menus and the majority of hud elements have been added to a curved surface. The curved effect means you don’t need to strain your eyes when looking at corners of the menus. A menu scaling option has been added to increase or decrease the size of the menus for individual player comfort.

Curvy Menus

For certain cockpits, decorative panels which took up too much screen space have been removed. Flying the Argonaut now provides a much larger area view than before for your unobstructed viewing pleasure.

Performance Improvements

Flying through Hazard (Asteroid/Mine) fields will feel much smoother than the last update with code optimizations. For those still struggling with FPS on potato PC’s additional video options have been added to improve frame rates when flying through Hazards. The biggest gain will be seen by lowering the Asteroid Field Debris Density or turning it off.

Missile Seeking Behaviour Improvements

Missiles are better than ever with improved seeking and target re-acquisition logic. Missiles requiring a front-facing lock type (i.e. Heat Seeker, Image Rec) on a target have increased tracking the closer to the target preventing any last-second veering off bringing significant accuracy improvements.

Missiles entering a holding pattern (spinning around in circles) while they seek a new target will now use their full-throttle setting when a new target has been acquired and actively seeking. On the downside, you can no longer drag race your own missiles.

Is that all?

No! The above I can talk about in detail as they are already functional. Plans are afoot for more, including:

  • Improving lore and storyline progression to give the campaign more meaning in that aspect.
  • Various bug fixes and improvements to the ship selection screen and options menus.
  • Option to disable screen shake for those who suffer from motion sickness (Always disabled in VR)
  • Click to continue mode for transmissions. Which will be especially helpful for playing through the tutorial.
  • Showing the difficulty a campaign mission was completed on.
  • Improvements to The Gauntlet simulator mode (health and ammo regen to be added) to focus more on combat instead of managing ammo and fuel reserves.

Feeling the need for more missions?

Did you know Absolute Territory comes with its own mission editor? Use the same level editor used to create the Absolute Territory campaign missions to create, play, and share custom missions to the Steam Workshop.

This powerful level editor allows you to create conditions and instructions which respond to the player and other in-world events with an easy-to-use interface with plenty of help to get you started on the F1 key.

Create your own missions in the included editor

If you just want to jump into new missions visit the Absolute Territory workshop, subscribe to existing missions, jump into the game and choose the mission from the Simulator under Workshop missions game type.

Final Reminder

Don’t forget you can save 40% off Absolute Territory on SteamHumble StoreMicrosoft StoreItch.io, or Gamejolt. Be sure to leave a review as more constructive feedback will help towards choosing future developments.

Follow @abs_territory on Twitter for minor updates as I progress towards this major update release.

Warp Tunnel taking you to new horizons in VR

More shopping options: Absolute Territory on the Humble Store

I know there are gamer who have they preferred places of purchase. Therefore, I am pleased to announce Absolute Territory is available on the Humble Store. As any Humble customer expects, purchasing Absolute Territory on the Humble Store will provide you a Steam key.

To celebrate, Absolute Territory is on a limited time sale with 25% off until the 1st February 2021.

Absolute Territory Cover Art
Buy Absolute Territory on the Humble Store

What’s Upcoming – Steam Achievements and Leaderboards

Welcome along, pilots, to the latest news update for Absolute Territory. It’s just been over 6 weeks since Absolute Territory was released on Steam amidst hundreds of improvements and enhancements over several updates.

Today, I’m happy to reveal some of the new features that will be making themselves into the next update.

Steam Achievements

There will be 45 Steam Achievements to unlock across the Absolute Territory campaign and Level Editor. 43 of these are for the campaign, ranging from completing each mission, completing the campaigns across higher difficulty levels, and specific actions and objectives.

The 3 achievements in the Level Editor will help guide you from creating a simple mission towards discovering the tools to design more complex and compelling adventures to share on the Steam Workshop.

Steam Leaderboards

How good of a pilot are you? Now you can find out! Steam Leaderboards have been added to Squadron and Gauntlet game modes, replacing the local leaderboard. You are no longer competing against yourself. See how you stack up against your friends and the rest world!

absolute territory

Absolute Territory is available to buy on Steam

Absolute Territory update 1.1.0 brings improved HUD art, additional 3rd person views, improved missile experience, additional enhancements, and improvements.

The latest update for Absolute Territory (Ver 1.1.0) has been published and brings more than 50 individual additions, improvements, and bug fixes.

Heads Up Display (HUD) art improvements
As mentioned in the last news update, I’ve been busily improving the existing in-flight HUD elements, covering the primary, secondary, shield & armor, speed, and range bars along with targeting brackets and waypoint indicators.

These have been designed to draw your eyes towards them when needed, i.e. when taking a lot of damage, and provide a significantly better experience in the presentation of information at a glance.

Improved HUD displays

Based on your feedback, waypoints are now context-sensitive depending on the required usage. Find yourself in an asteroid field and the waypoint will no longer confusingly tell you to use your autopilot, but to exit the hazard first!

New 3rd Person Views

Increase your situational awareness in 3rd person with additional sides and rear views. You can also toggle the HUD on/off (which was added quietly in the last update).

Fly-by external side view
Shocking external rear view

Waypoints

Improved visual indicators for waypoints for better “at a glance” awareness.

  • Broken with a line: Autopilot required but obstructed (either by hazard or nearby enemy)
  • Broken: Autopilot required
  • Unbroken: Can be reached without the need of autopilot
Waypoint States

Improved missile experience for starting mission
The introductory experience for missiles was not as fun as it could have been. Due, in part, to including the Javelin Heat Seeker missile in the loadout when going up against fast-moving enemies. It just didn’t have enough time to reach the exposed tailpipe of its target before it had turned around, therefore losing its lock on the heat signature.

Introducing the Lancea Friend or Foe missile, with significantly improved tracking ability over Heat Seeking variants but with a lower explosive yield. To make up for the lower yield, the base ammo count has been increased.

The existing Spiculum Image Recognition missile has had its steering velocity/acceleration reduced in-line with other seeking missiles which will bring better accuracy, and less wild behavior when being launched.

Random Crashes on AMD Graphics Cards

There was an issue for AMD Graphics Card owners where Absolute Territory would randomly crash. This was related to the Unity version used to build the game. I’ve updated to a newer version of Unity which has fixed this issue.

Full Patch Notes1.1.0 (20200928)
Overview – Improved the majority of in-flight HUD elements. Added additional views to 3rd person. Improved missile experience for starting missions. Various improvements and bugfixes.

Try the demo or buy now on steam

https://store.steampowered.com/app/1130880/

Unity
Amend – Updated Unity to 2019.4.10f1
Amend – Updated TextMeshPro to 2.1.1
Amend – Updates Jobs to 0.2.10
Amend – Updated HybridRenderer to 0.5.2
Amend – Updated NodeCanvas to 3.1.0
Amend – Updated Rewired to 1.1.36.1
Amend – Updated Aura 2 to 2.1.14

General
Added – Default display name for all vessels, used for when the Display Name field is not populated within the Level Editor
Added – Short description for selected Campaign Mission, underneath the campaign drop-down box within the Campaign Menu.

Amend – Radar blips no longer use the camera space for position calculations
Amend – Moved Level Editor button from the Simulator Menu to the Main Menu to make it more obvious

Missions
Amend – Adv Tutorial 201: Killing the Vomitoria too quickly would prevent any further progression

Gameplay
Added – Added Lancea FF Missile

Amend – Replaced Javelin HS with Lancea FF missile as a loadout in the first 3 campaign missions, for a better missile introductory experience
Amend – Spiculum Missile: Reduced Steering from 120 to 90 DPS on all axis
Amend – Spiculum Missile: Reduced Steering Acceleration from 240 to 135

Fixed – Null Reference Exceptions when exiting or restarting a mission during the Autopilot cinematic
Fixed – AI afterburning no longer causes the player camera to shake

Visuals
Added – In-flight External Camera Views

Amend – In-flight HUD graphical improvements across the majority of HUD elements
Amend – Waypoint Icon now context-sensitive based on Local Waypoint or Autopilot destination
Amend – Waypoint Indicator text now displays “Exit Hazard” if within a hazard zone and “Use Autopilot” when out of hazard for static waypoints
Amend – Reduced size of Help Glyph icons
Amend – Help Glyphs, Missile Alert, and Received Transmission Text now positions and resizes based on required usage
Amend – Help Glyphs: Controller Glyphs no longer disappear when interacting with the mouse, and will remember the last used controller
Amend – Missile Alert warning now has a bar representing the distance of the closest missile locked onto the player
Amend – Unintentionally removed Depth of Field effect, when the effect is enabled, from the 1st person cockpit, but looks better for it
Amend – First Person Neutral Camera Sway reduced from 0.25 to 0.15, for less noticeable effect on the cross-hair (if you focus too much on it)
Amend – Increased size of Explosion_003 M (Missile Explosions) Particle Scale from 14 to 20, to make these explosion effects stand out more at a distance

Fixed – Video Options post-processing effects no longer defaults to on when progressing to the next mission
Fixed – AI piloted ships using Hi-Rez assets no longer use opaque cockpit models to reveal there is no actual pilot!