Getting Garbage Collection for Free

Automotive
JavaScript performance continues to be one of the key aspects of Chrome's values, especially when it comes to enabling a smooth experience. Starting in Chrome 41, V8 takes advantage of a new technique to increase the responsiveness of web applications by hiding expensive memory management operations inside of small, otherwise unused chunks of idle time. As a result, web developers should expect smoother scrolling and buttery animations with much reduced jank due to garbage collection.

Many modern language engines such as Chrome's V8 JavaScript engine dynamically manage memory for running applications so that developers don't need to worry about it themselves. The engine periodically passes over the memory allocated to the application, determines which data is no longer needed, and clears it out to free up room. This process is known as garbage collection.

In Chrome, we strive to deliver a smooth, 60 frames per second (FPS) visual experience. Although V8 already attempts to perform garbage collection in small chunks, larger garbage collection operations can and do occur at unpredictable times -- sometimes in the middle of an animation -- pausing execution and preventing Chrome from hitting that 60 FPS goal.

Chrome 41 included a task scheduler for the Blink rendering engine which enables prioritization of latency-sensitive tasks to ensure Chrome remains responsive and snappy. As well as being able to prioritize work, this task scheduler has centralized knowledge of how busy the system is, what tasks need to be performed and how urgent each of these tasks are. As such, it can estimate when Chrome is likely to be idle and roughly how long it expects to remain idle.

An example of this occurs when Chrome is showing an animation on a web page. The animation will update the screen at 60 FPS, giving Chrome around 16.6 ms of time to perform the update. As such, Chrome will start work on the current frame as soon as the previous frame has been displayed, performing input, animation and frame rendering tasks for this new frame. If Chrome completes all this work in less than 16.6 ms, then it has nothing else to do for the remaining time until it needs to start rendering the next frame. Chrome’s scheduler enables V8 to take advantage of this idle time period by scheduling special idle tasks when Chrome would otherwise be idle.

Figure 1: Frame rendering with idle tasks.

Idle tasks are special low-priority tasks which are run when the scheduler determines it is in an idle period. Idle tasks are given a deadline which is the scheduler's estimate of how long it expects to remain idle. In the animation example in Figure 1, this would be the time at which the next frame should start being drawn. In other situations (e.g., when no on-screen activity is happening) this could be the time when the next pending task is scheduled to be run, with an upper bound of 50 ms to ensure that Chrome remains responsive to unexpected user input. The deadline is used by the idle task to estimate how much work it can do without causing jank or delays in input response.

Garbage collection done in the idle tasks are hidden from critical, latency-sensitive operations. This means that these garbage collection tasks are done for “free”. In order to understand how V8 does this, it is worth reviewing V8’s current garbage collection strategy.

Deep dive into V8’s garbage collection engine

V8 uses a generational garbage collector with the Javascript heap split into a small young generation for newly allocated objects and a large old generation for long living objects. Since most objects die young, this generational strategy enables the garbage collector to perform regular, short garbage collections in the smaller young generation (known as scavenges), without having to trace objects in the old generation.

The young generation uses a semi-space allocation strategy, where new objects are initially allocated in the young generation’s active semi-space. Once that semi-space becomes full, a scavenge operation will move live objects to the other semi-space. Objects which have been moved once already are promoted to the old generation and are considered to be long-living. Once the live objects have been moved, the new semi-space becomes active and any remaining dead objects in the old semi-space are discarded.

The duration of a young generation scavenge therefore depends on the size of live objects in the young generation. A scavenge will be fast (<1 ms) when most of the objects become unreachable in the young generation. However, if most objects survive a scavenge, the duration of the scavenge may be significantly longer.

A major collection of the whole heap is performed when the size of live objects in the old generation grows beyond a heuristically-derived limit. The old generation uses a mark-and-sweep collector with several optimizations to improve latency and memory consumption. Marking latency depends on the number of live objects that have to be marked, with marking of the whole heap potentially taking more than 100 ms for large web applications. In order to avoid pausing the main thread for such long periods, V8 has long had the ability to incrementally mark live objects in many small steps, with the aim to keep each marking steps below 5 ms in duration.

After marking, the free memory is made available again for the application by sweeping the whole old generation memory. This task is performed concurrently by dedicated sweeper threads. Finally, memory compaction is performed to reduce memory fragmentation in the old generation. This task may be very time-consuming and is only performed if memory fragmentation is an issue.

In summary, there are four main garbage collection tasks:
  1. Young generation scavenges, which usually are fast
  2. Marking steps performed by the incremental marker, which can be arbitrarily long depending on the step size
  3. Full garbage collections, which may take a long time
  4. Full garbage collections with aggressive memory compaction, which may take a long time, but clean up fragmented memory
In order to perform these operations in idle periods, V8 posts garbage collection idle tasks to the scheduler. When these idle tasks are run they are provided with a deadline by which they should complete. V8’s garbage collection idle time handler evaluates which garbage collection tasks should be performed in order to reduce memory consumption, while respecting the deadline to avoid future jank in frame rendering or input latency.

The garbage collector will perform a young generation scavenge during an idle task if the application’s measured allocation rate shows that the young generation may be full before the next expected idle period. Additionally, it calculates the average time taken by recent scavenge tasks in order to predict the duration of future scavenges and ensure that it doesn’t violate idle task deadlines.

When the size of live objects in the old generation is close to the heap limit, incremental marking is started. Incremental marking steps can be linearly scaled by the number of bytes that should be marked. Based on the average measured marking speed, the garbage collection idle time handler tries to fit as much marking work as possible into a given idle task.

A full garbage collection is scheduled during an idle tasks if the old generation is almost full and if the deadline provided to the task is estimated to be long enough to complete the collection. The collection pause time is predicted based on the marking speed multiplied by the number of allocated objects. Full garbage collections with additional compaction are only performed if the webpage has been idle for a significant amount of time.

Performance evaluation

In order to evaluate the impact of running garbage collection during idle time, we used Chrome’s Telemetry performance benchmarking framework to evaluate how smoothly popular websites scroll while they load. We benchmarked the top 25 sites on a Linux workstation as well as typical mobile sites on an Android Nexus 6 smartphone, both of which open popular webpages (including complex webapps such as Gmail, Google Docs and YouTube) and scroll their content for a few seconds. Chrome aims to keep scrolling at 60 FPS for a smooth user experience.

Figure 2 shows the percentage of garbage collection that was scheduled during idle time. The workstation’s faster hardware results in more overall idle time compared to the Nexus 6, thereby enabling a greater percentage of garbage collection to be scheduled during this idle time (43% compared to 31% on the Nexus 6) resulting in about 7% improvement on our jank metric.

Figure 2: The percentage of garbage collection that occurs during idle time. 


As well as improving the smoothness of page rendering, these idle periods also provide an opportunity to perform more aggressive garbage collection when the page becomes fully idle. Recent improvements in Chrome 45 take advantage of this to drastically reduce the amount of memory consumed by idle foreground tabs. Figure 3 shows a sneak peek at how memory usage of Gmail’s JavaScript heap can be reduced by about 45% when it becomes idle, compared to the same page in Chrome 43.

Figure 3: Memory usage for latest version of Chrome 45 (left) vs Chrome 43 on Gmail.

These improvements demonstrate that it is possible to hide garbage collection pauses by being smarter about when expensive garbage collection operations are performed. Web developers no longer have to fear the garbage collection pause, even when targeting silky smooth 60 FPS animations. Stay tuned for more improvements as we push the bounds of garbage collection scheduling.

Posted by Hannes Payer and Ross McIlroy, Idle Garbage Collectors
Automotive
11:52:00 AM

Automotive technology

Automotive

Labels

1904 Columbus 1940 Ford 1964 Worlds Fair 1969 Camaro 1969 Dodge Coronet Super Bee 2014 2016 Sales 2017 The Bad 8 2017 The Good 12 3 wheeler 4 G 407 407 ex2 427 AC Cobra 440 six pack 442 4x 4x4 55 Chevy 57 Chevy 5th wheel AAR abandoned abs abuse by law enforcement AC Cobra Acadian accessories accident Acoustic processing Active noise control (ANC) Acura Acura Reviews adaptive cruise control ADAS Adobe AIR ads adventurers advertising aerodynamics Aircraft engines airlines airplane Airstream Alfa Alfa Romeo Alfa-Romeo All Cars Rankings All SUV Rankings All Vehicle Rankings Alpina Alpine AMBR winner ambulance AMC America's greatest photographers American LaFrance amphib AMX AMX-3 Andorra Andrew Poliak Android Andy Gryc anti lock braking system App World Apps Arab-Supercar area controller Ariel-Nomad ARM-based devices art Art Arfons Art Deco artist Asset management system Aston Martin Aston-Martin atv auction Audi Audi Reviews audio Augmented reality Austin Austin Healey Australia Austria Auto Accident Attorney auto car donate auto car donation Auto Donate Auto Donation California Auto hobby books Auto Sales By Brand auto show Auto Story in Pictures Wednesday auto taxi Autocar automobile automobile donation AUTOMOBILE INSURANCE automobile parts automobile safety system automobule donate Autonomous cars Awards awesome B 29 B 52 BAIC Baja racing Baker banners barn find barn finds barnfind barnfinds Barracuda Barris barum BatBerry Batman Batteries battery beautiful engine Beautiful paint before and after Belgium Bello's belly tanker Bentley Best Sellers Best Selling American Cars Best Selling Cars Best Selling Luxury Best Selling SUVs Best Selling Trucks Best Selling Vehicles bicycle bicycles Big 3 Swap Meet big wheel bike messengers bike rack biofuel biography BlackBerry BlackBerry Radar BlackBerry-QNX blink code blink code checkup blink code error blink code troubleshooting Blog blogs BMW BMW Audi Mercedes Benz Daimler jeep GM toyota Chrysler VW volkswagon nissan infiniti ford unique rare Bntley boardtrack Boats boattail Bonneville book review bookmobile Boss 302 Boss 429 brake brakes braking system Brand Marketshare brass era breedlove Brewster Brian Salisbury Bricklin bridge British Britten brochure Bugatti Buick Bulgaria burnout bus Buses buying selling cash tips money advice BYD c C-type Jag Cadillac Cadillac Reviews Camaro Can Am Canada Canada 2016 Sales Canada All Cars Rankings Canada All SUV Rankings Canada All Vehicle Rankings Canada Auto Sales Canada Auto Sales By Brand Canada Best Sellers Canada Compact Car Sales Canada December 2016 Canada Entry Luxury Car Sales Canada February 2017 Canada January 2017 Canada Large Car Sales Canada Large Luxury Car Sales Canada Large Luxury SUV Sales Canada Large SUV Sales Canada March 2017 Canada Midsize Car Sales Canada Midsize Luxury Car Sales Canada Midsize Luxury SUV Sales Canada Midsize SUV Sales Canada Minivan Sales Canada November 2016 Canada October 2016 Canada Premium Sporty Car Sales Canada September 2016 Canada Small Luxury SUV Sales Canada Small SUV Sales Canada Sporty Car Sales Canada Truck Sales Canada Van Sales Canada Worst Sellers car care car chase scene car clubs car collections car collectors Car Donate car donate california car donation Car Donations California Car or the Future car wash carbs carrozzeria cart caterpillar tracked vehicle CCS celebrities celebrity Certicom CES CESA 2012 CESA 3.0 Chademo Challenger Chaparral Charger Charity Charity auction charity car donation Charity Car Donation Program Charity Car With Your Credit Card cheating Checker Chery Chevelle Chevrolet Chevrolet Reviews Chevy 2 China chopper Christian Sobottka Christie Christmas Chrysler Citroen Citroën classics cleaning clip Cloud connectivity CO2 Cobra Cobra Daytona Coupe Cobra Mustang Cobra Torino COE Cogent collection collector College Colombia commercial common rail direct injection Compact Car Sales companies comparison compliment components components of anti-lock braking system concept Concept car Concept team Connected Car construction Consumer Electronics Show consumers Contest convertible Coronet Corvair corvette Corvettes Costa Rica coupe coventry cragar crash crde crdi Croatia Crosley crossover Cruise 4 Kids crypto cryptography CTS Cuda Cunningham Curtiss Aerocar Custom customer satisfaction cutaway display cycle car Cyclone Cyprus Czech Republic dacia Daihatsu Dan Gurney dart Datsun Daytona ddis DDS dealers Dealership Dean Martin December 2016 Degree delivery truck Delorean Delphi Demon Denmark Derek Kuhn design deuce devices Dick Landy dicor Digital instrument clusters digital spark ignition Diner with car theme direction injection Disney display diy Dodge domain controller Donate Donate A Car Tax Deduction Donate Automobile To Charity Donate Car To Charity Tax Deduction Donate Vehicles To Charity donation donation auto car donation vehicles to charity Doug Newcomb Drag racing drag strip Dragonsnake dragsters DREAM drifting Driven Driver distraction driving assistance drunk driver DS dtsi dual carbs dual engined dualie Ducati dump truck dvla E-type Jag ECC economy ECU Ecuador electric electric car Electric cars electromagnetic brake Elliptic Curve Cryptography EMF Emil Dautovic Endurance racing engine engine accessories Engine sound enhancement engines Entry Luxury Car Sales enzo Erskine Essex estate Estonia etc EUCAR Europe EV Business Case Evel Knievel event experience experiment extreme sports video F1 Factor-Aurelio Factory lightweight Factory race car Fairlane Falcon Fast boot Fast-Charging FCA FCEV February 2017 Ferrari Fiat Fiat Botafogo finance Finland fips fire engine fire fighting fire trucks Firebird Firestone firetrucks Fisker flamejob fleet management Ford ford escort Ford Reviews Fordson tractor Forecasts FOTA found around the neighborhood France Franklin Free Car Donation Freescale french fuel fuel injection fuel injection system Fuel Tanker fuel-cell fun Funny car Futurliner gadgets Galpin Ford game garage garner gas mileage gas stations Gasser Gauges GCBC Awards GCBC Most Popular Geely Gene Winfield General Motors German Germany give your car to charity GM GM MyLink GNX Go cart good news Goodwood Goodyear gourmet food vans GPU Graham Gran Prix Grand National Roadster Show 2017 Grand Sport Corvette Graph Great Wall Motors Greece green Green car Gremlin GT GT 350 GT 40 GT 500 gt40 GTO GTX Gulf race car Gullwing Guy Martin Hands-free systems Harley Harley Davidson hauler Hawaii helicopter hemi hemmings Hennessey Henry J hero Hertz hire Hispano-Suiza historical history HMIs Holden Hollywood Holman Moody Honda Honda Reviews Honda Sales Hong Kong Hood ornaments hood scoops Horizon 2020 horse carriage horse wagon host blog info about auto Hot rods Hot Wheels Housekeeping How To Donate How To Donate A Car For Tax Deduction How To Donate Car To Charity how to donation car to charity HRM HTML5 Hudson Hummer humor humour Humvee Hungary Hupmobile Hurst Hurst SC Rambler hybrid Hybrid cars hydrogen hypervisor Hyundai Hyundai Reviews Ian Roussel Iceland ID4 Car ignition IIoT immitation Impala india Indian Indianapolis industry news infiniti Infiniti Reviews Info infographic informative Infotainment Injury Lawyer Innotrans innova innovation innovative instrument panel insurance intake Intel interior International Harvester Internet of Things Internet radio invitation IoT Ireland iris iris details iris engine details iris technical Isetta Iskenderian Isky Isle of Man ISO 26262 Israel issues Isuzu Italian Italy ITS ITU IVI Jaguar January 2017 Japan Japanese Javelin Jay Leno Jean-François Tarabbia Jeep Jeep Wrangler JLR John D'Agostino John Deere John Wall Justin Moon jv Kaivan Karimi Kandi kawasaki Ken Block Kerry Johnson Kia kids Kim Cairns Kissel Kombi Kroy Zeviar Kurtis La Carrera Panamerica lace paint Lamborghini Lamborghini Revuelto Lancia Land Cruiser Land Rover Land Rover Sales land speed record holder Land-Rover Large Car Sales Large Luxury Car Sales Large Luxury SUV Sales Large SUV Sales Larry Wood LaSalle Latvia launch law enforcement lawnmower laws Le Mans legends Leno Lexus license plates Lidar Life Insurance limited Lincoln Lincoln MKZ Linda Campbell Linda Vaughn links lists Lithuania live Loans Locomobile logging train logging trucks Lola London to Brighton Looking for EV's Los Angeles Lotus lowrider LSR Luxembourg luxury Lyft Lynn Gayowski Mach 1 machine shop Mack Mad Max magazine magazines magic iris mags Malaysia March 2017 Mario Andretti Mark Donohue marketing Marketshare Maserati Matt Watson Maverick Mazda Mazda Reviews MB McLaren mechanic Megan Alink meme Memory Lane Men Micro Mercedes Mercedes Benz Mercedes-Benz Mercer Cobra Mercury Metallica Metro Mexico Miata microkernal Midsize Car Sales Midsize Luxury Car Sales Midsize Luxury SUV Sales Midsize SUV Sales Military Miller race car mini mini bike miniature Minivan Sales MirrorLink mission-critical Mitsubishi Miura MMI Mobile connectivity Mobile World Congress mod top Model Model A model T modifications Momo Monaco Monster Truck Moon Moon eyes Mopar Mopar parts Morgan Morocco morons mot Motor shows motor wheel Motorcycle Motorcycles motorhomes Mouse movie movies mpv Multicore Munsters Muntz muscle cars musclecars museum music video Mustang NAIAS Nancy Young Nascar Nash Navigation naza neglec neglected Netherlands new tv show New York New Zealand news ni Nissan Nissan Reviews Nomad Norway nos nose art Nova November 2016 Nurburgring Object Management group October 2016 off roading offenhauser Oldsmobile OMG Online College OnStar Opel Open source Open standards OpenGL ES option orders original owner Ormond Beach land speed racing pace car Packard Pagani Paige pamphlet panel paint Paris to Peking race parking parts Patryk Fournier Paul Leroux Paul Newman Paul Sykes Pebble Beach pedal car perodua personal Peter McCarthy petrol petroliana Peugeot Phoenix Injury photographer photography pics pictures Pierce Arrow Pike's Peak Pinin Farina pinstriping Pit row Pits Pixar PKI plank road PlayBook Plymouth Point Grey Camera Poland pole wheel police Polysynch Pontiac Porsche Porsche 917 Porsche Carrera Portugal POSIX pre 1930's gas station Premium Sporty Car Sales President of the USA Preview prices prius project prooject Proton prototype PSA Peugeot Citroen public key cryptography Pullman QNX QNX CAR QNX Garage QNX OS Qualcomm quiz quote race cars racing racing. LSR Radar radio Raid Data rail railcars railroad ralliart Rally rallying Ram range rover rant Rapid Transit System advertsing rare Real time Innovations recall recommended shop record setter Red Bull Sports Reference vehicle Reliability Rémi Bastien RemoteLink Renault Renesas Renntransporter rentals REO repair reports resarch research restoration restoration shop review Richard Bishop Ridler Award Winner rims river bank cars road and highway Road Runner roadster Robot OS Robot wars Roewe Roger Penske Rolls Royce Romain Saha Romania ROS Roth RTI RTI Connext rumble seat Russia Ruxton RV Safety Safety systems safety-certified sales Sales By Model Sales Stats samba sampan Saoutchik Satellite satnav Scaglietti scallops Scat Pack SCCA racecar School bus sci-fi Scooter SCORE Baja trucks Scott Pennock Scout sculpture Security sedan segway semi sensor extension cable sensor fusion September 2016 service service repair automotive vehicle car buying selling mission statement blog free broker shay drive locomotive Shelby shifter shop Show cars sidecars signs skateboarding Skoda slicks slingshot dragster Slovakia Slovenia Small Luxury SUV Sales Small SUV Sales Smart Smartphones snow machines snowmobile Soapbox South Africa South Korea Sox and Martin Spain spare tire spark ignition spark plug spark plugs Spatial auditory displays special edition Mustangs Speech interfaces speed limit Speed Record speedfest speedster sports car sports cars Sporty Car Sales spy shots spyker Sri Lanka SS SS/AH Stagecoach Stanley Station Wagon steam locomotive steam powered steam shovel steampunk steering wheel Steve McQueen Stig Stirling Moss Stolen streamliner street cars Street Van studebaker stunt stunts Stutz Stutz Blackhawk Subaru Sunbeam Super Bee Super Stock Superbird Supercar supercharger survey suv Suzuki Sweden Swift Switzerland System development Life Cycle Tablets Tach takeover tank tata tata magic iris tata vehicles tax Tax Deduction For Car Donation taxi taxi cab TCS tdi teardrop technical technology Telematics Telematics Detroit Telematics Update tempo Tempo Matador Terlingua Racing Team Terry Staycer Tesla test testdrive Texas Instruments The Race Of Gentlemen Thomas Bloor thoughts three wheeler Thunderbird ticket Tiger Tim Neil Tina Jeffrey tips tires tool tool kit toolbox tools Top Gear top ten list Torino tour bus tourbus towtruck Toyota Toyota Entune Toyota Reviews tractor trailer train train wreck trains Trans Am transmission Transporter Traval trike Triumph trivia trolley Troy Trepanier truck Truck Sales trucking trucks Tucker turbocharger turbojet turbonique Turkey tv tv cars twin spark type 1 type 2 tyres UAE Uber UK UK Auto Sales UK Best Sellers uk market Ukraine Unimog unique University of Waterloo Unser unusual unveil upgrade US US 2016 Sales US All Cars Rankings US All SUV Rankings US All Vehicle Rankings US Auto Sales US Auto Sales By Brand US Best Sellers US Compact Car Sales US December 2016 US Entry Luxury Car Sales US February 2017 US January 2017 US Large Car Sales US Large Luxury Car Sales US Large Luxury SUV Sales US Large SUV Sales US March 2017 US Midsize Car Sales US Midsize Luxury Car Sales US Midsize Luxury SUV Sales US Midsize SUV Sales US Minivan Sales US Navy US November 2016 US October 2016 US September 2016 US Small Luxury SUV Sales US Small SUV Sales US Sporty Car Sales US Truck Sales US US Auto Sales US Van Sales US Worst Sellers USA used cars V2X van Van Sales vauxhall VeDeCoM Vehicle Donation California Velodyne Vespa Video vintage vintage racing Virtual mechanic Virtualization VOIP Guide Volkswagen Volkswagen Reviews Volkswagen Sales Volvo Von Dutch vote VW VW bug W3C wagon train wall of death washer washer fluid Watson's Webinars website what is donation what is it wheel speed sensor wheelchair White williams Willys windshield washer wing Wireless framework women woodlight headlights Woody work truck working principle of anti-lock braking system workshop World Worst Sellers wreck Wrongful Death WW1 WW2 XK SS Yoram Berholtz Yoshiki Chubachi Z 11 Z-28 Z28 zamboni ZL1 Zotye