Fall cleaning: Optimizing V8 memory consumption

Automotive
Memory consumption is an important dimension in the JavaScript virtual machine performance trade-off space. Over the last few months the V8 team analyzed and significantly reduced the memory footprint of several websites that were identified as representative of modern web development patterns. In this blog post we present the workloads and tools we used in our analysis, outline memory optimizations in the garbage collector, and show how we reduced memory consumed by V8’s parser and its compilers.

Benchmarks

In order to profile V8 and discover optimizations that have impact for the largest number of users, it is crucial to define workloads that are reproducible, meaningful, and simulate common real-world JavaScript usage scenarios. A great tool for this task is Telemetry, a performance testing framework that runs scripted website interactions in Chrome and records all server responses in order to enable predictable replay of these interactions in our test environment. We selected a set of popular news, social, and media websites and defined the following common user interactions for them:

A workload for browsing news and social websites:
  1. Open a popular news or social website, e.g. hackernews.
  2. Click on the first link.
  3. Wait until the new website is loaded.
  4. Scroll down a few pages.
  5. Click the back button.
  6. Click on the next link on the original website and repeat steps 3-6 a few times.
A workload for browsing media website:
  1. Open an item on a popular media website, e.g. a video on YouTube.
  2. Consume that item by waiting for a few seconds.
  3. Click on the next item and repeat steps 2-3 a few times.
Once a workflow is captured, it can be replayed as often as needed against a development version of Chrome, for example each time there is new version of V8. During playback, V8’s memory usage is sampled at fixed time intervals to obtain a meaningful average. The benchmarks can be found here.

Memory Visualization

One of the main challenges when optimizing for performance in general is to get a clear picture of internal VM state to track progress or weigh potential tradeoffs. For optimizing memory consumption, this means keeping accurate track of V8’s memory consumption during execution. There are two categories of memory that must be tracked: memory allocated to V8’s managed heap and memory allocated on the C++ heap. The V8 Heap Statistics feature is a mechanism used by developers working on V8 internals to get deep insight into both. When the --trace-gc-object-stats flag is specified when running Chrome (M54 or newer) or the d8 command line interface, V8 dumps memory-related statistics to the console. We built a custom tool, the v8 heap visualizer, to visualize this output. The tool shows a timeline-based view for both the managed and C++ heaps. The tool also provides a detailed breakdown of the memory usage of certain internal data types and size-based histograms for each of those types.

A common workflow during our optimization efforts involves selecting an instance type that takes up a large portion of the heap in the timeline view, as depicted in Figure 1. Once an instance type is selected, the tool then shows a distribution of uses of this type. In this example we selected V8’s internal FixedArray data structure, which is an untyped vector-like container used ubiquitously in all sorts of places in the VM. Figure 2 shows a typical FixedArray distribution, where we can see that the majority of memory can be attributed to a specific FixedArray usage scenario. In this case FixedArrays are used as the backing store for sparse JavaScript arrays (what we call DICTIONARY_ELEMENTS). With this information it is possible to refer back to the actual code and either verify whether this distribution is indeed the expected behavior or whether an optimization opportunity exists. We used the tool to identify inefficiencies with a number of internal types.

Figure 1: Timeline view of managed heap and off-heap memory

Figure 2: Distribution of instance type

Figure 3 shows C++ heap memory consumption, which consists primarily of zone memory (temporary memory regions used by V8 used for  a short period of time; discussed in more detail below).  Since zone memory is used most extensively by the V8 parser and compilers, the spikes correspond to parsing and compilation events. A well-behaved execution consists only of spikes, indicating that memory is freed as soon as it is no longer needed. In contrast, plateaus (i.e. longer periods of time with higher memory consumption) indicate that there is room for optimization.

Figure 3: Zone memory

Early adopters can also try out the integration into Chrome’s tracing infrastructure. Therefore you need to run the latest Chrome Canary with --track-gc-object-stats and capture a trace including the category v8.gc_stats. The data will then show up as V8.GC_Object_Stats event.

JavaScript Heap Size Reduction

There is an inherent trade-off between garbage collection throughput, latency, and memory consumption. For example, garbage collection latency (which causes user-visible jank) can be reduced by using more memory to avoid frequent garbage collection invocations. For low-memory mobile devices, i.e. devices with under 512M of RAM, prioritizing latency and throughput over memory consumption may result in out-of-memory crashes and suspended tabs on Android.

To better balance the right tradeoffs for these low-memory mobile devices, we introduced a special memory reduction mode which tunes several garbage collection heuristics to lower memory usage of the JavaScript garbage collected heap. 1) At the end of a full garbage collection, V8’s heap growing strategy determines when the next garbage collection will happen based on the amount of live objects with some additional slack. In memory reduction mode, V8 will use less slack resulting in less memory usage due to more frequent garbage collections. 2) Moreover this estimate is treated as a hard limit, forcing unfinished incremental marking work to finalize in the main garbage collection pause. Normally, when not in memory reduction mode, unfinished incremental marking work may result in going over this limit arbitrarily to trigger the main garbage collection pause only when marking is finished. 3) Memory fragmentation is further reduced by performing more aggressive memory compaction.

Figure 4 depicts some of the improvements on low memory devices since Chrome M53. Most noticeably, the average V8 heap memory consumption of the mobile New York Times benchmark reduced by about 66%. Overall, we observed a 50% reduction of average V8 heap size on this set of benchmarks.

Figure 4: V8 heap memory reduction since M53 on low memory devices

Another optimization introduced recently not only reduces memory on low-memory devices but beefier mobile and desktop machines. Reducing the V8 heap page size from 1M to 512KB results in a smaller memory footprint when not many live objects are present and lower overall memory fragmentation up to 2x. It also allows V8 to perform more compaction work since smaller work chunks allow more work to be done in parallel by the memory compaction threads.

Zone Memory Reduction

In addition to the JavaScript heap, V8 uses off-heap memory for internal VM operations. The largest chunk of memory is allocated through memory areas called zones. Zones are a type of  region-based memory allocator which enables fast allocation and bulk deallocation where all zone allocated memory is freed at once when the zone is destroyed. Zones are used throughout V8’s parser and compilers. 

One of the major improvements in M55 comes from reducing memory consumption during background parsing. Background parsing allows V8 to parse scripts while a page is being loaded. The memory visualization tool helped us discover that the background parser would keep an entire zone alive long after the code was already compiled. By immediately freeing the zone after compilation, we reduced the lifetime of zones significantly which resulted in reduced average and peak memory usage.

Another improvement results from better packing of fields in abstract syntax tree nodes generated by the parser. Previously we relied on the C++ compiler to pack fields together where possible. For example, two booleans just require two bits and should be located within one word or within the unused fraction of the previous word. The C++ compiler doesn’t not always find the most compressed packing, so we instead manually pack bits. This not only results in reduced peak memory usage, but also improved parser and compiler performance.

Figure 5 shows the peak zone memory improvements since M54 which reduced by about 40% on average over the measured websites. 

Figure 5: V8 peak zone memory reduction since M54 on desktop

Over the next months we will continue our work on reducing the memory footprint of V8. We have more zone memory optimizations planned for the parser and we plan to focus on devices ranging from 512M-1G of memory.

Update: All the improvements discussed above reduce the Chrome 55 overall memory consumption by up to 35% on low-memory devices compared to Chrome 53.  Other device segments will only benefit from the zone memory improvements.

Posted by the V8 Memory Sanitation Engineers Ulan Degenbaev, Michael Lippautz, Hannes Payer, and Toon Verwaest.





Automotive
4:55: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