Jump to Table of Contents Collapse Sidebar

P1640R1
Error size benchmarking: Redux

Published Proposal,

This version:
https://wg21.link/P1640R1
Author:
(National Instruments)
Audience:
WG21; DG
Project:
ISO/IEC JTC1/SC22/WG21 14882: Programming Language — C++
Source:
github.com/ben-craig/error_bench/blob/master/bench_blog.bs

Abstract

The author measures size costs of error handling approaches. Exceptions are big, std::abort and integer error codes are small.

To make progress, we need better data on costs and performance to evaluate the - often simplistic and narrowly focused - solutions suggested. — Direction for ISO C++ [P0939R2]

1. Introduction

In this paper, we will look at the size costs of error handling. We’ll break things down into one-time costs and incremental costs, and subdivide by costs paid for error neutral functions, raising an error, and handling an error.

2. Changes

R1 of this paper removed the discussion on how exceptions are implemented, and reduced the set of error handling strategies down to throwing exceptions, return codes, abort, and noexcept abort. This is to make the paper and charts easier to read. The data is the same.

R1 renamed the "stripped" cases to "baremetal" cases, to better frame where those numbers would be applicable.

3. Measuring methodology

All benchmarks lie. It’s important to know how a benchmark is set up so that the useful parts can be distinguished from the misleading parts.

The specific build flags can be found in Appendix B. Following is a brief summary.

MSVC 2019 was used for MSVC x86 and MSVC x64 builds. The /d2FH4 flag described in [MoFH4] was used, and /EHs was used when exceptions were on.

GCC 7.3.1 from the Red Hat Developer Toolset 7.1 was used for my GCC builds. The Linux x64 platform was targeted.

Clang 8.0.0, libc++, and libc++abi was used for my Clang builds. The Linux x64 platform was targeted. The system linker and C library leaked in to this build. The system GCC was GCC 4.8.4 from Ubuntu 14.04.3.

All the binaries are optimized for size, rather than speed.

All the binaries are built with static runtimes, so that we can also see the costs of the error handling runtime machinery. For many people, this is a sunk cost. If the cost of the runtime machinery isn’t of interest, then don’t pay attention to the one-time costs, and just look at the incremental costs. Sizes were not calculated by just doing the "easy" thing and comparing the on-disk sizes of the resulting programs. Programs have lots and lots of padding internal to them due to alignment constraints, and that padding can mask or inflate small cost changes. Instead, the size is calculated by summing the size of all the non-code sections, and by summing the size of each function in the code sections. Measuring the size of a function is a little tricky, as the compiler doesn’t emit that information directly. There are often padding instructions between consecutive functions. My measurements omit the padding instructions so that we can see code size differences as small as one byte.

Measurements are also included where the size of some data sections related to unwinding are omitted. On x64 Linux, programs can have an .eh_frame and .eh_frame_hdr section that can help with emitting back traces. x64 Windows has similar sections named .xdata and .pdata. These sections aren’t sufficient to implement C++ exception handling, and they don’t go away when exceptions are turned off. On Linux and Windows, these sections should be considered a sunk cost, but on more exotic platforms, it is reasonable to omit those sections, as stack trace costs may not be tolerable. These measurements are all labeled as "baremetal". x86 Windows doesn’t have these sections, so the "baremetal" measurements are the same as the regular measurements.

Note that on Linux, the entire user mode program can be statically linked. This is the program under test, the C++ runtime, the C runtime, and any OS support. On Windows, the program, the C++ runtime, and the C runtime can be statically linked, but the OS support (kernel32.dll) is still distinct. With this in mind, refrain from comparing the one-time MSVC sizes to the Clang and GCC sizes, as it isn’t comparing the same set of functionality.

These benchmarks are run on very small programs. On larger programs, various code and data deduplication optimizations could substantially change the application-level costs of error handling. [MoFH4] documents the kinds of deduplication that MSVC 2019 performs.

4. Starter test cases

To start with, we will look at code similar to the following:
struct Dtor {~Dtor() {}};
int global_int = 0;
void callee() {/* will raise an error one day*/}
void caller() {
  Dtor d;
  callee();
  global_int = 0;
}
int main() { 
  caller();
  return global_int;
}
This code has some important properties for future comparisons.

In the actual tests all the function bodies are in separate .cpp files, and link-time / whole-program optimizations aren’t used. If they had been used, the entire program would get optimized away, removing our ability to measure error handling differences.

The above program is a useful template when using exceptions or std::abort as an error handling mechanism, but it won’t work as well for error codes. So we mutate the program like so...

int callee() {return 0;}
int caller() {
  Dtor d;
  int e = callee();
  if (e)
    return e;
  global_int = 0;
  return e;
}
This is pretty typical integer return value code, without any macro niceties.

Most of the programs were built with exceptions turned off, but the throw_* cases and noexcept_abort all had exceptions turned on in the program.

Data on many more error handling strategies can be found in R0 of this paper.

Expository code for all the cases can be found in Appendix C. The actual code used for the benchmark can be found on my github.

5. Measurements

5.1. Initial error neutral size cost

My first batch of measurements is comparing each of the mechanisms to the baremetal.abort test case. This lets us focus on the incremental costs of the other mechanisms.

Warning! Logarithmic axis! Linear version here

Warning! Logarithmic axis! Linear version here

These tables show us that the one-time cost for exceptions is really high (6KB on MSVC x86, 382KB on Clang x64), and the one time cost for unwind information is pretty high too (6KB on MSVC x64, 57KB on Clang). Note that noexcept_abort has the same cost as regular abort right now. If everything is noexcept, the exception machinery costs are not incurred.

5.2. Incremental error neutral size cost

To measure the incremental cost of error neutral code, the code will be updated as follows:
void callee2(int amount) {
  global_int += amount;
  // will error one day
}
void caller2(int amount) {
  Dtor d;
  callee2(amount);
  global_int += amount;
}
int main() { 
  caller();
  caller2(0);
  return global_int;
}
The "2" versions of these functions are slightly different than the original versions in order to avoid optimization where identical code is de-duplicated (COMDAT folding). Each error handling case was updated to the idiomatic form that had the same semantics as this error neutral form. Here are the incremental numbers:

The delta between the best and the worst is much smaller in the incremental error neutral measurements than in the one-time cost measurements. abort and return values were always cheaper than exceptions, even with included unwind information.

5.3. Initial size cost of signaling an error

What happens when an error is signaled first time? What’s the one-time cost of that first error?
void callee() {
  if (global_int == INT_MAX)
    throw 1;
}

Warning! Logarithmic axis! Linear version here

Warning! Logarithmic axis! Linear version here

On MSVC, there are multiple ways to build with exceptions "on". This experiment was built with /EHs, which turns on exceptions in a C++ conforming manner. The Microsoft recommended flag is /EHsc, which turns on exceptions for all C++ functions, but assumes that extern "C" functions won’t throw. This is a useful, though non-conforming option. The trick is that the noexcept_abort callee() implementation calls abort(), and that’s an extern "C" function that isn’t marked as noexcept, so we suddenly need to pay for all the exception handling costs that we had been avoiding by making everything noexcept. We can’t easily make the C runtime, or other people’s code noexcept. We don’t see this on GCC and Clang because the C library they are calling marks abort as __attribute__ ((__nothrow__)), and that lets them avoid generating the exception machinery.

GCC’s first throw costs look worse than Clang’s because Clang paid a lot of those costs even before there was a throw.

5.4. Incremental size cost of signaling an error

void callee2(int amount) {
  if (global_int + amount == INT_MAX)
    throw 1;
  global_int += amount;
}

These numbers are all over the place. Here are some highlights:

5.5. Initial size cost for handling an error

To get the initial handling costs, we’ll rewrite main to look something like this...
int main() {
  try {
    caller();
  } catch (int) {
    global_int = 0;
  }
  caller2(0);
  return global_int;
}
abort results won’t be included here, because there is no "handling" of an abort call in C++. The environment needs to handle it and restart the process, reboot the system, or relaunch the rocket.

Here we see that the initial catch cost exceptions is high compared to the alternatives.

5.6. Incremental size cost for handling an error

Now for the incremental code, and the associated costs.
int main() {
  try {
    caller();
  } catch (int) {
    global_int = 0;
  }
  try {
    caller2(0);
  } catch (int) {
    global_int = 0;
  }
  return global_int;
}
Note that this is measuring the cost of handling a second error within a single function. If the error handling were split over multiple functions, the cost profile may be different.

6. Conclusion

Exceptions and on-by-default unwinding information are reasonable error handling strategies in many environments, but they don’t serve all needs in all use cases. C++ needs standards conforming ways to avoid exception and unwind overhead on platforms that are size constrained. C++ is built on the foundation that you don’t pay for what you don’t use, and that you can’t write the language abstractions better by hand. This paper provides evidence that you can write error handling code by hand that results in smaller code than the equivalent exception throwing code if all you use is terminate semantics or an integer’s worth of error information. In each of the six test cases, terminate and integer return values beat exceptions on size, even before stripping out unwind information.

7. Acknowledgments

Simon Brand, Niall Douglas, Brad Keryan, Reid Kleckner, Modi Mo, Herb Sutter, John McFarlane, Ben Saks, and Richard Smith provided valuable review commentary on R0 of this paper.

Thanks to Lawrence Crowl, for asking the question "what if everything were noexcept?".

Charts generated with [ECharts].

Appendix A: Why no speed measurements?

[P1886] contains speed measurements for various error handling strategies.

Appendix B: The build flags

MSVC

The compiler and flags are the same for 32-bit and 64-bit builds, except that the 32-bit linker uses /machine:x86 and the 64-bit linker uses /machine:x64

Compiler marketing version: Visual Studio 2019

Compiler toolkit version: 14.20.27508

cl.exe version: 19.20.27508.1

Compiler codegen flags (no exceptions): /GR /Gy /Gw /O1 /MT /d2FH4 /std:c++latest /permissive- /DNDEBUG

Compiler codegen flags (with exceptions): /EHs /GR /Gy /Gw /O1 /MT /d2FH4 /std:c++latest /permissive- /DNDEBUG

Linker flags: /OPT:REF /release /subsystem:CONSOLE /incremental:no /OPT:ICF /NXCOMPAT /DYNAMICBASE /DEBUG *.obj

Clang x64

Toolchains used:

Compiler codegen flags (no exceptions): -fno-exceptions -Os -ffunction-sections -fdata-sections -std=c++17 -stdlib=libc++ -static -DNDEBUG

Compiler codegen flags (exceptions): -Os -ffunction-sections -fdata-sections -std=c++17 -stdlib=libc++ -static -DNDEBUG

Linking flags: -Wl,--gc-sections -pthread -static -static-libgcc -stdlib=libc++ *.o libc++abi.a

GCC x64

Toolchain used: GCC 7.3.1 from the Red Hat Developer Toolset 7.1

Compiler codegen flags (no exceptions): -fno-exceptions -Os -ffunction-sections -fdata-sections -std=c++17 -static

Compiler codegen flags (exceptions): -Os -ffunction-sections -fdata-sections -std=c++17 -static

Linking flags: -Wl,--gc-sections -pthread -static -static-libgcc -static-libstdc++ *.o

Appendix C: The code

As stated before, this isn’t the exact code that was benchmarked. In the benchmarked code, functions were placed in distinct translation units in order to avoid inlining. The following code is provided to demonstrate what the error handling code looks like.

Common support code

Expand to see code snippets All cases
struct Dtor {~Dtor() {}};
int global_int = 0;

throw_exception

class err_exception : public std::exception {
public:
  int val;
  explicit err_exception(int e) : val(e) {}
  const char *what() const noexcept override { return ""; }
};

Initial error neutral functions

This section lays the groundwork for future comparisons. All of these cases are capable of transporting error information from a future signaling site (callee) to a future catching site (main). No errors are signaled here, but the plumbing is in place.
Expand to see code snippets Default main function
int main() {
  caller();
  return global_int;
}
abort, throw_exception
void callee() {/* will raise an error one day*/}
void caller() {
  Dtor d;
  callee();
  global_int = 0;
}
noexcept_abort
void callee() noexcept {/* will raise an error one day*/}
void caller() noexcept {
  Dtor d;
  callee();
  global_int = 0;
}
return_val
int callee() noexcept {return 0;}
int caller() noexcept {
  Dtor d;
  int e = callee();
  if (e)
    return e;
  global_int = 0;
  return e;
}

Incremental error neutral functions

Here, we add an extra two functions with error transporting capabilities so that we can measure the incremental cost of error neutral functions. These functions need to be slightly different than the old functions in order to avoid deduplication optimizations.

In order to save on text length, the only functions that will be listed here are the functions were added or changed compared to the previous section.

Expand to see code snippets Default main function
int main() {
  caller();
  caller2(0);
  return global_int;
}
abort, throw_exception
void callee2(int amount) { global_int += amount; }
void caller2(int amount) {
  Dtor d;
  callee2(amount);
  global_int += amount;
}
noexcept_abort
void callee2(int amount) noexcept { global_int += amount; }
void caller2(int amount) noexcept {
  Dtor d;
  callee2(amount);
  global_int += amount;
}
return_val
int callee2(int amount) {
  global_int += amount;
  return 0;
}
int caller2(int amount) {
  Dtor d;
  int e = callee2(amount);
  if (e)
    return e;
  global_int += amount;
  return e;
}

Initial signaling of an error

Expand to see code snippets abort
void callee() {
  if (global_int == INT_MAX)
    abort();
}
noexcept_abort
void callee() noexcept {
  if (global_int == INT_MAX)
    abort();
}
return_val
int callee() {
  if (global_int == INT_MAX) {
    return 1;
  }
  return 0;
}
throw_exception
void callee() {
  if (global_int == INT_MAX)
    throw err_exception(1);
}

Incremental signaling of an error

Expand to see code snippets abort
void callee2(int amount) {
  if (global_int + amount == INT_MAX)
    abort();
  global_int += amount;
}
noexcept_abort
void callee2(int amount) noexcept {
  if (global_int + amount == INT_MAX)
    abort();
  global_int += amount;
}
return_val
int callee2(int amount) {
  if (global_int + amount == INT_MAX) {
    return 1;
  }
  global_int += amount;
  return 0;
}
throw_exception
void callee2(int amount) {
  if (global_int + amount == INT_MAX)
    throw err_exception(1);
  global_int += amount;
}

Initial handling of an error

Expand to see code snippets return_val
int main() {
  if (caller()) {
    global_int = 0;
  }
  caller2(0);
  return global_int;
}
return_struct
int main() {
  if (caller().error) {
    global_int = 0;
  }
  caller2(0);
  return global_int;
}
throw_exception
int main() {
  try { caller(); }
  catch (const std::exception &) {
    global_int = 0;
  }
  caller2(0);
  return global_int;
}

Incremental handling of an error

Expand to see code snippets return_val
int main() {
  if (caller()) {
    global_int = 0;
  }
  if (caller2(0)) {
    global_int = 0;
  }
  return global_int;
}
throw_exception
int main() {
  try { caller(); }
  catch (const std::exception &) {
    global_int = 0;
  }
  try { caller2(0); }
  catch (const std::exception &) {
    global_int = 0;
  }
  return global_int;
}

Appendix D: Linear graphs

Initial error neutral cost, linear

Logarithmic version of this graph with commentary

Initial cost of signaling an error, linear

Logarithmic version of this graph with commentary

References

Informative References

[ECharts]
ECharts. URL: https://ecomfe.github.io/echarts-doc/public/en/index.html
[MoFH4]
Modi Mo. Making C++ Exception Handling Smaller On x64. URL: https://devblogs.microsoft.com/cppblog/making-cpp-exception-handling-smaller-x64/
[P0939R2]
H. Hinnant; et al. Direction for ISO C++. URL: http://wg21.link/P0939R2
[P1886]
Ben Craig. Error speed benchmarking. URL: http://wg21.link/P1866
gger"))return i.dispatchAction({type:"updateAxisPointer",seriesIndex:r,dataIndex:a,position:n.position}),!0}},_tryShow:function(t,e){var i=t.target;if(this._tooltipModel){this._lastX=t.offsetX,this._lastY=t.offsetY;var n=t.dataByCoordSys;n&&n.length?this._showAxisTooltip(n,t):i&&null!=i.dataIndex?(this._lastDataByCoordSys=null,this._showSeriesItemTooltip(t,i,e)):i&&i.tooltip?(this._lastDataByCoordSys=null,this._showComponentItemTooltip(t,i,e)):(this._lastDataByCoordSys=null,this._hide(e))}},_showOrMove:function(t,e){var i=t.get("showDelay");e=P(e,this),clearTimeout(this._showTimout),i>0?this._showTimout=setTimeout(e,i):e()},_showAxisTooltip:function(t,e){var i=this._ecModel,n=this._tooltipModel,r=[e.offsetX,e.offsetY],a=[],o=[],s=Mv([e.tooltipOption,n]),l=this._renderMode,h=this._newLine,u={};_v(t,function(t){_v(t.dataByAxis,function(t){var e=i.getComponent(t.axisDim+"Axis",t.axisIndex),n=t.value,r=[];if(e&&null!=n){var s=sv(n,e.axis,i,t.seriesDataIndices,t.valueLabelOpt);C(t.seriesDataIndices,function(a){var h=i.getSeriesByIndex(a.seriesIndex),c=a.dataIndexInside,d=h&&h.getDataParams(c);if(d.axisDim=t.axisDim,d.axisIndex=t.axisIndex,d.axisType=t.axisType,d.axisId=t.axisId,d.axisValue=Nf(e.axis,n),d.axisValueLabel=s,d){o.push(d);var f,p=h.formatTooltip(c,!0,null,l);if(E(p)){f=p.html;var g=p.markers;v(u,g)}else f=p;r.push(f)}});var c=s;"html"!==l?a.push(r.join(h)):a.push((c?al(c)+h:"")+r.join(h))}})},this),a.reverse(),a=a.join(this._newLine+this._newLine);var c=e.position;this._showOrMove(s,function(){this._updateContentNotChangedOnAxis(t)?this._updatePosition(s,c,r[0],r[1],this._tooltipContent,o):this._showTooltipContent(s,a,o,Math.random(),r[0],r[1],c,void 0,u)})},_showSeriesItemTooltip:function(t,e,i){var n=this._ecModel,r=e.seriesIndex,a=n.getSeriesByIndex(r),o=e.dataModel||a,s=e.dataIndex,l=e.dataType,h=o.getData(),u=Mv([h.getItemModel(s),o,a&&(a.coordinateSystem||{}).model,this._tooltipModel]),c=u.get("trigger");if(null==c||"item"===c){var d,f,p=o.getDataParams(s,l),g=o.formatTooltip(s,!1,l,this._renderMode);E(g)?(d=g.html,f=g.markers):(d=g,f=null);var v="item_"+o.name+"_"+s;this._showOrMove(u,function(){this._showTooltipContent(u,d,p,v,t.offsetX,t.offsetY,t.position,t.target,f)}),i({type:"showTip",dataIndexInside:s,dataIndex:h.getRawIndex(s),seriesIndex:r,from:this.uid})}},_showComponentItemTooltip:function(t,e,i){var n=e.tooltip;if("string"==typeof n){n={content:n,formatter:n}}var r=new zs(n,this._tooltipModel,this._ecModel),a=r.get("content"),o=Math.random();this._showOrMove(r,function(){this._showTooltipContent(r,a,r.get("formatterParams")||{},o,t.offsetX,t.offsetY,t.position,e)}),i({type:"showTip",from:this.uid})},_showTooltipContent:function(t,e,i,n,r,a,o,s,l){if(this._ticket="",t.get("showContent")&&t.get("show")){var h=this._tooltipContent,u=t.get("formatter");o=o||t.get("position");var c=e;if(u&&"string"==typeof u)c=ll(u,i,!0);else if("function"==typeof u){var d=xv(function(e,n){e===this._ticket&&(h.setContent(n,l,t),this._updatePosition(t,o,r,a,h,i,s))},this);this._ticket=n,c=u(i,n,d)}h.setContent(c,l,t),h.show(t),this._updatePosition(t,o,r,a,h,i,s)}},_updatePosition:function(t,e,i,n,r,a,o){var s=this._api.getWidth(),l=this._api.getHeight();e=e||t.get("position");var h=r.getSize(),u=t.get("align"),c=t.get("verticalAlign"),d=o&&o.getBoundingRect().clone();if(o&&d.applyTransform(o.transform),"function"==typeof e&&(e=e([i,n],a,r.el,d,{viewSize:[s,l],contentSize:h.slice()})),O(e))i=wv(e[0],s),n=wv(e[1],l);else if(E(e)){e.width=h[0],e.height=h[1];var f=_l(e,{width:s,height:l});i=f.x,n=f.y,u=null,c=null}else if("string"==typeof e&&o){var p=function(t,e,i){var n=i[0],r=i[1],a=0,o=0,s=e.width,l=e.height;switch(t){case"inside":a=e.x+s/2-n/2,o=e.y+l/2-r/2;break;case"top":a=e.x+s/2-n/2,o=e.y-r-5;break;case"bottom":a=e.x+s/2-n/2,o=e.y+l+5;break;case"left":a=e.x-n-5,o=e.y+l/2-r/2;break;case"right":a=e.x+s+5,o=e.y+l/2-r/2}return[a,o]}(e,d,h);i=p[0],n=p[1]}else{p=function(t,e,i,n,r,a,o){var s=i.getOuterSize(),l=s.width,h=s.height;null!=a&&(t+l+a>n?t-=l+a:t+=a);null!=o&&(e+h+o>r?e-=h+o:e+=o);return[t,e]}(i,n,r,s,l,u?null:20,c?null:20);i=p[0],n=p[1]}if(u&&(i-=Iv(u)?h[0]/2:"right"===u?h[0]:0),c&&(n-=Iv(c)?h[1]/2:"bottom"===c?h[1]:0),t.get("confine")){p=function(t,e,i,n,r){var a=i.getOuterSize(),o=a.width,s=a.height;return t=Math.min(t+o,n)-o,e=Math.min(e+s,r)-s,t=Math.max(t,0),e=Math.max(e,0),[t,e]}(i,n,r,s,l);i=p[0],n=p[1]}r.moveTo(i,n)},_updateContentNotChangedOnAxis:function(t){var e=this._lastDataByCoordSys,i=!!e&&e.length===t.length;return i&&_v(e,function(e,n){var r=e.dataByAxis||{},a=(t[n]||{}).dataByAxis||[];(i&=r.length===a.length)&&_v(r,function(t,e){var n=a[e]||{},r=t.seriesDataIndices||[],o=n.seriesDataIndices||[];(i&=t.value===n.value&&t.axisType===n.axisType&&t.axisId===n.axisId&&r.length===o.length)&&_v(r,function(t,e){var n=o[e];i&=t.seriesIndex===n.seriesIndex&&t.dataIndex===n.dataIndex})})}),this._lastDataByCoordSys=t,!!i},_hide:function(t){this._lastDataByCoordSys=null,t({type:"hideTip",from:this.uid})},dispose:function(t,e){n.node||(this._tooltipContent.hide(),$g("itemTooltip",e))}}),ad({type:"showTip",event:"showTip",update:"tooltip:manuallyShowTip"},function(){}),ad({type:"hideTip",event:"hideTip",update:"tooltip:manuallyHideTip"},function(){}),Tl.registerSubTypeDefaulter("dataZoom",function(){return"slider"});var Tv=["cartesian2d","polar","singleAxis"];var Cv,Dv,Av,kv,Pv=(Dv=["axisIndex","axis","index","id"],Av=D(Cv=(Cv=["x","y","z","radius","angle","single"]).slice(),dl),kv=D(Dv=(Dv||[]).slice(),dl),function(t,e){C(Cv,function(i,n){for(var r={name:i,capital:Av[n]},a=0;a=0}(t,o)&&function(t,n){var r=!1;return e(function(e){C(i(t,e)||[],function(t){n.records[e.name][t]&&(r=!0)})}),r}(t,o)&&(n(t,o),a=!0)}return o};function n(t,n){n.nodes.push(t),e(function(e){C(i(t,e)||[],function(t){n.records[e.name][t]=!0})})}}var Ov=C,zv=Gs,Bv=function(t,e,i,n){this._dimName=t,this._axisIndex=e,this._valueWindow,this._percentWindow,this._dataExtent,this._minMaxSpan,this.ecModel=n,this._dataZoomModel=i};function Ev(t,e){var i=t.getAxisModel(),n=t._percentWindow,r=t._valueWindow;if(n){var a=Xs(r,[0,500]);a=Math.min(a,20);var o=e||0===n[0]&&100===n[1];i.setRange(o?null:+r[0].toFixed(a),o?null:+r[1].toFixed(a))}}Bv.prototype={constructor:Bv,hostedBy:function(t){return this._dataZoomModel===t},getDataValueWindow:function(){return this._valueWindow.slice()},getDataPercentWindow:function(){return this._percentWindow.slice()},getTargetSeriesModels:function(){var t=[],e=this.ecModel;return e.eachSeries(function(i){if(a=i.get("coordinateSystem"),M(Tv,a)>=0){var n=this._dimName,r=e.queryComponents({mainType:n+"Axis",index:i.get(n+"AxisIndex"),id:i.get(n+"AxisId")})[0];this._axisIndex===(r&&r.componentIndex)&&t.push(i)}var a},this),t},getAxisModel:function(){return this.ecModel.getComponent(this._dimName+"Axis",this._axisIndex)},getOtherAxisModel:function(){var t,e,i,n=this._dimName,r=this.ecModel,a=this.getAxisModel();return"x"===n||"y"===n?(e="gridIndex",t="x"===n?"y":"x"):(e="polarIndex",t="angle"===n?"radius":"angle"),r.eachComponent(t+"Axis",function(t){(t.get(e)||0)===(a.get(e)||0)&&(i=t)}),i},getMinMaxSpan:function(){return g(this._minMaxSpan)},calculateDataWindow:function(t){var e=this._dataExtent,i=this.getAxisModel().axis.scale,n=this._dataZoomModel.getRangePropMode(),r=[0,100],a=[t.start,t.end],o=[];return Ov(["startValue","endValue"],function(e){o.push(null!=t[e]?i.parse(t[e]):null)}),Ov([0,1],function(t){var s=o[t],l=a[t];"percent"===n[t]?(null==l&&(l=r[t]),s=i.parse(Ws(l,r,e,!0))):l=Ws(s,e,r,!0),o[t]=s,a[t]=l}),{valueWindow:zv(o),percentWindow:zv(a)}},reset:function(t){if(t===this._dataZoomModel){var e=this.getTargetSeriesModels();this._dataExtent=function(t,e,i){var n=[1/0,-1/0];Ov(i,function(t){var i=t.getData();i&&Ov(i.mapDimension(e,!0),function(t){var e=i.getApproximateExtent(t);e[0]n[1]&&(n[1]=e[1])})}),n[1]0?0:NaN);var o=i.getMax(!0);null!=o&&"dataMax"!==o&&"function"!=typeof o?e[1]=o:r&&(e[1]=a>0?a-1:NaN),i.get("scale",!0)||(e[0]>0&&(e[0]=0),e[1]<0&&(e[1]=0))}(t,n),n}(this,this._dimName,e);var i=this.calculateDataWindow(t.option);this._valueWindow=i.valueWindow,this._percentWindow=i.percentWindow,function(t){var e=t._minMaxSpan={},i=t._dataZoomModel;Ov(["min","max"],function(n){e[n+"Span"]=i.get(n+"Span");var r=i.get(n+"ValueSpan");if(null!=r&&(e[n+"ValueSpan"]=r,null!=(r=t.getAxisModel().axis.scale.parse(r)))){var a=t._dataExtent;e[n+"Span"]=Ws(a[0]+r,a,[0,100],!0)}})}(this),Ev(this)}},restore:function(t){t===this._dataZoomModel&&(this._valueWindow=this._percentWindow=null,Ev(this,!0))},filterData:function(t,e){if(t===this._dataZoomModel){var i=this._dimName,n=this.getTargetSeriesModels(),r=t.get("filterMode"),a=this._valueWindow;"none"!==r&&Ov(n,function(t){var e=t.getData(),n=e.mapDimension(i,!0);n.length&&("weakFilter"===r?e.filterSelf(function(t){for(var i,r,o,s=0;sa[1];if(h&&!u&&!c)return!0;h&&(o=!0),u&&(i=!0),c&&(r=!0)}return o&&i&&r}):Ov(n,function(i){if("empty"===r)t.setData(e.map(i,function(t){return function(t){return t>=a[0]&&t<=a[1]}(t)?t:NaN}));else{var n={};n[i]=a,e.selectRange(n)}}),Ov(n,function(t){e.setApproximateExtent(a,t)}))})}}};var Rv=C,Nv=Pv,Fv=ud({type:"dataZoom",dependencies:["xAxis","yAxis","zAxis","radiusAxis","angleAxis","singleAxis","series"],defaultOption:{zlevel:0,z:4,orient:null,xAxisIndex:null,yAxisIndex:null,filterMode:"filter",throttle:null,start:0,end:100,startValue:null,endValue:null,minSpan:null,maxSpan:null,minValueSpan:null,maxValueSpan:null,rangeMode:null},init:function(t,e,i){this._dataIntervalByAxis={},this._dataInfo={},this._axisProxies={},this.textStyleModel,this._autoThrottle=!0,this._rangePropMode=["percent","percent"];var n=Wv(t);this.mergeDefaultAndTheme(t,i),this.doInit(n)},mergeOption:function(t){var e=Wv(t);v(this.option,t,!0),this.doInit(e)},doInit:function(t){var e=this.option;n.canvasSupported||(e.realtime=!1),this._setDefaultThrottle(t),Vv(this,t),Rv([["start","startValue"],["end","endValue"]],function(t,i){"value"===this._rangePropMode[i]&&(e[t[0]]=null)},this),this.textStyleModel=this.getModel("textStyle"),this._resetTarget(),this._giveAxisProxies()},_giveAxisProxies:function(){var t=this._axisProxies;this.eachTargetAxis(function(e,i,n,r){var a=this.dependentModels[e.axis][i],o=a.__dzAxisProxy||(a.__dzAxisProxy=new Bv(e.name,i,this,r));t[e.name+"_"+i]=o},this)},_resetTarget:function(){var t=this.option,e=this._judgeAutoMode();Nv(function(e){var i=e.axisIndex;t[i]=rr(t[i])},this),"axisIndex"===e?this._autoSetAxisIndex():"orient"===e&&this._autoSetOrient()},_judgeAutoMode:function(){var t=this.option,e=!1;Nv(function(i){null!=t[i.axisIndex]&&(e=!0)},this);var i=t.orient;return null==i&&e?"orient":e?void 0:(null==i&&(t.orient="horizontal"),"axisIndex")},_autoSetAxisIndex:function(){var t=!0,e=this.get("orient",!0),i=this.option,n=this.dependentModels;if(t){var r="vertical"===e?"y":"x";n[r+"Axis"].length?(i[r+"AxisIndex"]=[0],t=!1):Rv(n.singleAxis,function(n){t&&n.get("orient",!0)===e&&(i.singleAxisIndex=[n.componentIndex],t=!1)})}t&&Nv(function(e){if(t){var n=[],r=this.dependentModels[e.axis];if(r.length&&!n.length)for(var a=0,o=r.length;a0?100:20}},getFirstTargetAxisModel:function(){var t;return Nv(function(e){if(null==t){var i=this.get(e.axisIndex);i.length&&(t=this.dependentModels[e.axis][i[0]])}},this),t},eachTargetAxis:function(t,e){var i=this.ecModel;Nv(function(n){Rv(this.get(n.axisIndex),function(r){t.call(e,n,r,this,i)},this)},this)},getAxisProxy:function(t,e){return this._axisProxies[t+"_"+e]},getAxisModel:function(t,e){var i=this.getAxisProxy(t,e);return i&&i.getAxisModel()},setRawRange:function(t,e){var i=this.option;Rv([["start","startValue"],["end","endValue"]],function(e){null==t[e[0]]&&null==t[e[1]]||(i[e[0]]=t[e[0]],i[e[1]]=t[e[1]])},this),!e&&Vv(this,t)},getPercentRange:function(){var t=this.findRepresentativeAxisProxy();if(t)return t.getDataPercentWindow()},getValueRange:function(t,e){if(null!=t||null!=e)return this.getAxisProxy(t,e).getDataValueWindow();var i=this.findRepresentativeAxisProxy();return i?i.getDataValueWindow():void 0},findRepresentativeAxisProxy:function(t){if(t)return t.__dzAxisProxy;var e=this._axisProxies;for(var i in e)if(e.hasOwnProperty(i)&&e[i].hostedBy(this))return e[i];for(var i in e)if(e.hasOwnProperty(i)&&!e[i].hostedBy(this))return e[i]},getRangePropMode:function(){return this._rangePropMode.slice()}});function Wv(t){var e={};return Rv(["start","end","startValue","endValue","throttle"],function(i){t.hasOwnProperty(i)&&(e[i]=t[i])}),e}function Vv(t,e){var i=t._rangePropMode,n=t.get("rangeMode");Rv([["start","startValue"],["end","endValue"]],function(t,r){var a=null!=e[t[0]],o=null!=e[t[1]];a&&!o?i[r]="percent":!a&&o?i[r]="value":n?i[r]=n[r]:a&&(i[r]="percent")})}var Hv=tu.extend({type:"dataZoom",render:function(t,e,i,n){this.dataZoomModel=t,this.ecModel=e,this.api=i},getTargetCoordInfo:function(){var t=this.dataZoomModel,e=this.ecModel,i={};return t.eachTargetAxis(function(t,n){var r=e.getComponent(t.axis,n);if(r){var a=r.getCoordSysModel();a&&function(t,e,i,n){for(var r,a=0;aa&&(e[1-n]=e[n]+u.sign*a),e});function Zv(t,e){var i=t[e]-t[1-e];return{span:Math.abs(i),sign:i>0?-1:i<0?1:e?-1:1}}function Xv(t,e){return Math.min(e[1],Math.max(e[0],t))}var Yv=Io,jv=Ws,qv=Gs,Uv=P,$v=C,Kv="horizontal",Qv=5,Jv=["line","bar","candlestick","scatter"],tm=Hv.extend({type:"dataZoom.slider",init:function(t,e){this._displayables={},this._orient,this._range,this._handleEnds,this._size,this._handleWidth,this._handleHeight,this._location,this._dragging,this._dataShadowInfo,this.api=e},render:function(t,e,i,n){tm.superApply(this,"render",arguments),vu(this,"_dispatchZoomAction",this.dataZoomModel.get("throttle"),"fixRate"),this._orient=t.get("orient"),!1!==this.dataZoomModel.get("show")?(n&&"dataZoom"===n.type&&n.from===this.uid||this._buildView(),this._updateView()):this.group.removeAll()},remove:function(){tm.superApply(this,"remove",arguments),mu(this,"_dispatchZoomAction")},dispose:function(){tm.superApply(this,"dispose",arguments),mu(this,"_dispatchZoomAction")},_buildView:function(){var t=this.group;t.removeAll(),this._resetLocation(),this._resetInterval();var e=this._displayables.barGroup=new ci;this._renderBackground(),this._renderHandle(),this._renderDataShadow(),t.add(e),this._positionGroup()},_resetLocation:function(){var t=this.dataZoomModel,e=this.api,i=this._findCoordRect(),n={width:e.getWidth(),height:e.getHeight()},r=this._orient===Kv?{right:n.width-i.x-i.width,top:n.height-30-7,width:i.width,height:30}:{right:7,top:i.y,width:30,height:i.height},a=bl(t.option);C(["right","top","width","height"],function(t){"ph"===a[t]&&(a[t]=r[t])});var o=_l(a,n,t.padding);this._location={x:o.x,y:o.y},this._size=[o.width,o.height],"vertical"===this._orient&&this._size.reverse()},_positionGroup:function(){var t=this.group,e=this._location,i=this._orient,n=this.dataZoomModel.getFirstTargetAxisModel(),r=n&&n.get("inverse"),a=this._displayables.barGroup,o=(this._dataShadowInfo||{}).otherAxisInverse;a.attr(i!==Kv||r?i===Kv&&r?{scale:o?[-1,1]:[-1,-1]}:"vertical"!==i||r?{scale:o?[-1,-1]:[-1,1],rotation:Math.PI/2}:{scale:o?[1,-1]:[1,1],rotation:Math.PI/2}:{scale:o?[1,1]:[1,-1]});var s=t.getBoundingRect([a]);t.attr("position",[e.x-s.x,e.y-s.y])},_getViewExtent:function(){return[0,this._size[0]]},_renderBackground:function(){var t=this.dataZoomModel,e=this._size,i=this._displayables.barGroup;i.add(new Yv({silent:!0,shape:{x:0,y:0,width:e[0],height:e[1]},style:{fill:t.get("backgroundColor")},z2:-40})),i.add(new Yv({shape:{x:0,y:0,width:e[0],height:e[1]},style:{fill:"transparent"},z2:0,onclick:P(this._onClickPanelClick,this)}))},_renderDataShadow:function(){var t=this._dataShadowInfo=this._prepareDataShadowInfo();if(t){var e=this._size,i=t.series,n=i.getRawData(),r=i.getShadowDim?i.getShadowDim():t.otherDim;if(null!=r){var a=n.getDataExtent(r),o=.3*(a[1]-a[0]);a=[a[0]-o,a[1]+o];var s,l=[0,e[1]],h=[0,e[0]],u=[[e[0],0],[0,0]],c=[],d=h[1]/(n.count()-1),f=0,p=Math.round(n.count()/e[0]);n.each([r],function(t,e){if(p>0&&e%p)f+=d;else{var i=null==t||isNaN(t)||""===t,n=i?0:jv(t,a,l,!0);i&&!s&&e?(u.push([u[u.length-1][0],0]),c.push([c[c.length-1][0],0])):!i&&s&&(u.push([f,0]),c.push([f,0])),u.push([f,n]),c.push([f,n]),f+=d,s=i}});var g=this.dataZoomModel;this._displayables.barGroup.add(new _o({shape:{points:u},style:x({fill:g.get("dataBackgroundColor")},g.getModel("dataBackground.areaStyle").getAreaStyle()),silent:!0,z2:-20})),this._displayables.barGroup.add(new wo({shape:{points:c},style:g.getModel("dataBackground.lineStyle").getLineStyle(),silent:!0,z2:-19}))}}},_prepareDataShadowInfo:function(){var t=this.dataZoomModel,e=t.get("showDataShadow");if(!1!==e){var i,n=this.ecModel;return t.eachTargetAxis(function(r,a){C(t.getAxisProxy(r.name,a).getTargetSeriesModels(),function(t){if(!(i||!0!==e&&M(Jv,t.get("type"))<0)){var o,s=n.getComponent(r.axis,a).axis,l={x:"y",y:"x",radius:"angle",angle:"radius"}[r.name],h=t.coordinateSystem;null!=l&&h.getOtherAxis&&(o=h.getOtherAxis(s).inverse),l=t.getData().mapDimension(l),i={thisAxis:s,series:t,thisDim:r.name,otherDim:l,otherAxisInverse:o}}},this)},this),i}},_renderHandle:function(){var t=this._displayables,e=t.handles=[],i=t.handleLabels=[],n=this._displayables.barGroup,r=this._size,a=this.dataZoomModel;n.add(t.filler=new Yv({draggable:!0,cursor:em(this._orient),drift:Uv(this._onDragMove,this,"all"),onmousemove:function(t){Pt(t.event)},ondragstart:Uv(this._showDataInfo,this,!0),ondragend:Uv(this._onDragEnd,this),onmouseover:Uv(this._showDataInfo,this,!0),onmouseout:Uv(this._showDataInfo,this,!1),style:{fill:a.get("fillerColor"),textPosition:"inside"}})),n.add(new Yv($o({silent:!0,shape:{x:0,y:0,width:r[0],height:r[1]},style:{stroke:a.get("dataBackgroundColor")||a.get("borderColor"),lineWidth:1,fill:"rgba(0,0,0,0)"}}))),$v([0,1],function(t){var r=Ts(a.get("handleIcon"),{cursor:em(this._orient),draggable:!0,drift:Uv(this._onDragMove,this,t),onmousemove:function(t){Pt(t.event)},ondragend:Uv(this._onDragEnd,this),onmouseover:Uv(this._showDataInfo,this,!0),onmouseout:Uv(this._showDataInfo,this,!1)},{x:-1,y:0,width:2,height:2}),o=r.getBoundingRect();this._handleHeight=Vs(a.get("handleSize"),this._size[1]),this._handleWidth=o.width/o.height*this._handleHeight,r.setStyle(a.getModel("handleStyle").getItemStyle());var s=a.get("handleColor");null!=s&&(r.style.fill=s),n.add(e[t]=r);var l=a.textStyleModel;this.group.add(i[t]=new ho({silent:!0,invisible:!0,style:{x:0,y:0,text:"",textVerticalAlign:"middle",textAlign:"center",textFill:l.getTextColor(),textFont:l.getFont()},z2:10}))},this)},_resetInterval:function(){var t=this._range=this.dataZoomModel.getPercentRange(),e=this._getViewExtent();this._handleEnds=[jv(t[0],[0,100],e,!0),jv(t[1],[0,100],e,!0)]},_updateInterval:function(t,e){var i=this.dataZoomModel,n=this._handleEnds,r=this._getViewExtent(),a=i.findRepresentativeAxisProxy().getMinMaxSpan(),o=[0,100];Gv(e,n,r,i.get("zoomLock")?"all":t,null!=a.minSpan?jv(a.minSpan,o,r,!0):null,null!=a.maxSpan?jv(a.maxSpan,o,r,!0):null);var s=this._range,l=this._range=qv([jv(n[0],r,o,!0),jv(n[1],r,o,!0)]);return!s||s[0]!==l[0]||s[1]!==l[1]},_updateView:function(t){var e=this._displayables,i=this._handleEnds,n=qv(i.slice()),r=this._size;$v([0,1],function(t){var n=e.handles[t],a=this._handleHeight;n.attr({scale:[a/2,a/2],position:[i[t],r[1]/2-a/2]})},this),e.filler.setShape({x:n[0],y:0,width:n[1]-n[0],height:r[1]}),this._updateDataInfo(t)},_updateDataInfo:function(t){var e=this.dataZoomModel,i=this._displayables,n=i.handleLabels,r=this._orient,a=["",""];if(e.get("showDetail")){var o=e.findRepresentativeAxisProxy();if(o){var s=o.getAxisModel().axis,l=this._range,h=t?o.calculateDataWindow({start:l[0],end:l[1]}).valueWindow:o.getDataValueWindow();a=[this._formatLabel(h[0],s),this._formatLabel(h[1],s)]}}var u=qv(this._handleEnds.slice());function c(t){var e=bs(i.handles[t].parent,this.group),o=Ss(0===t?"right":"left",e),s=this._handleWidth/2+Qv,l=Ms([u[t]+(0===t?-s:s),this._size[1]/2],e);n[t].setStyle({x:l[0],y:l[1],textVerticalAlign:r===Kv?"middle":o,textAlign:r===Kv?o:"center",text:a[t]})}c.call(this,0),c.call(this,1)},_formatLabel:function(t,e){var i=this.dataZoomModel,n=i.get("labelFormatter"),r=i.get("labelPrecision");null!=r&&"auto"!==r||(r=e.getPixelPrecision());var a=null==t||isNaN(t)?"":"category"===e.type||"time"===e.type?e.scale.getLabel(Math.round(t)):t.toFixed(Math.min(r,20));return z(n)?n(t,a):B(n)?n.replace("{value}",a):a},_showDataInfo:function(t){t=this._dragging||t;var e=this._displayables.handleLabels;e[0].attr("invisible",!t),e[1].attr("invisible",!t)},_onDragMove:function(t,e,i){this._dragging=!0;var n=Ms([e,i],this._displayables.barGroup.getLocalTransform(),!0),r=this._updateInterval(t,n[0]),a=this.dataZoomModel.get("realtime");this._updateView(!a),r&&a&&this._dispatchZoomAction()},_onDragEnd:function(){this._dragging=!1,this._showDataInfo(!1),!this.dataZoomModel.get("realtime")&&this._dispatchZoomAction()},_onClickPanelClick:function(t){var e=this._size,i=this._displayables.barGroup.transformCoordToLocal(t.offsetX,t.offsetY);if(!(i[0]<0||i[0]>e[0]||i[1]<0||i[1]>e[1])){var n=this._handleEnds,r=(n[0]+n[1])/2,a=this._updateInterval("all",i[0]-r);this._updateView(),a&&this._dispatchZoomAction()}},_dispatchZoomAction:function(){var t=this._range;this.api.dispatchAction({type:"dataZoom",from:this.uid,dataZoomId:this.dataZoomModel.id,start:t[0],end:t[1]})},_findCoordRect:function(){var t;if($v(this.getTargetCoordInfo(),function(e){if(!t&&e.length){var i=e[0].model.coordinateSystem;t=i.getRect&&i.getRect()}}),!t){var e=this.api.getWidth(),i=this.api.getHeight();t={x:.2*e,y:.2*i,width:.6*e,height:.6*i}}return t}});function em(t){return"vertical"===t?"ns-resize":"ew-resize"}Fv.extend({type:"dataZoom.inside",defaultOption:{disabled:!1,zoomLock:!1,zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!1,preventDefaultMouseMove:!0}});var im="\0_ec_interaction_mutex";function nm(t,e){return!!function(t){return t[im]||(t[im]={})}(t)[e]}function rm(t){this.pointerChecker,this._zr=t,this._opt={};var e=P,i=e(am,this),n=e(om,this),r=e(sm,this),a=e(lm,this),o=e(hm,this);Mt.call(this),this.setPointerChecker=function(t){this.pointerChecker=t},this.enable=function(e,s){this.disable(),this._opt=x(g(s)||{},{zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!1,preventDefaultMouseMove:!0}),null==e&&(e=!0),!0!==e&&"move"!==e&&"pan"!==e||(t.on("mousedown",i),t.on("mousemove",n),t.on("mouseup",r)),!0!==e&&"scale"!==e&&"zoom"!==e||(t.on("mousewheel",a),t.on("pinch",o))},this.disable=function(){t.off("mousedown",i),t.off("mousemove",n),t.off("mouseup",r),t.off("mousewheel",a),t.off("pinch",o)},this.dispose=this.disable,this.isDragging=function(){return this._dragging},this.isPinching=function(){return this._pinching}}function am(t){if(!(Lt(t)||t.target&&t.target.draggable)){var e=t.offsetX,i=t.offsetY;this.pointerChecker&&this.pointerChecker(t,e,i)&&(this._x=e,this._y=i,this._dragging=!0)}}function om(t){if(this._dragging&&dm("moveOnMouseMove",t,this._opt)&&"pinch"!==t.gestureEvent&&!nm(this._zr,"globalPan")){var e=t.offsetX,i=t.offsetY,n=this._x,r=this._y,a=e-n,o=i-r;this._x=e,this._y=i,this._opt.preventDefaultMouseMove&&Pt(t.event),cm(this,"pan","moveOnMouseMove",t,{dx:a,dy:o,oldX:n,oldY:r,newX:e,newY:i})}}function sm(t){Lt(t)||(this._dragging=!1)}function lm(t){var e=dm("zoomOnMouseWheel",t,this._opt),i=dm("moveOnMouseWheel",t,this._opt),n=t.wheelDelta,r=Math.abs(n),a=t.offsetX,o=t.offsetY;if(0!==n&&(e||i)){if(e){var s=r>3?1.4:r>1?1.2:1.1;um(this,"zoom","zoomOnMouseWheel",t,{scale:n>0?s:1/s,originX:a,originY:o})}if(i){var l=Math.abs(n);um(this,"scrollMove","moveOnMouseWheel",t,{scrollDelta:(n>0?1:-1)*(l>3?.4:l>1?.15:.05),originX:a,originY:o})}}}function hm(t){nm(this._zr,"globalPan")||um(this,"zoom",null,t,{scale:t.pinchScale>1?1.1:1/1.1,originX:t.pinchX,originY:t.pinchY})}function um(t,e,i,n,r){t.pointerChecker&&t.pointerChecker(n,r.originX,r.originY)&&(Pt(n.event),cm(t,e,i,n,r))}function cm(t,e,i,n,r){r.isAvailableBehavior=P(dm,null,i,n),t.trigger(e,r)}function dm(t,e,i){var n=i[t];return!t||n&&(!B(n)||e.event[n+"Key"])}ad({type:"takeGlobalCursor",event:"globalCursorTaken",update:"update"},function(){}),I(rm,Mt);var fm="\0_ec_dataZoom_roams";function pm(t,e){var i=vm(t),n=e.dataZoomId,r=e.coordId;C(i,function(t,i){var a=t.dataZoomInfos;a[n]&&M(e.allCoordIds,r)<0&&(delete a[n],t.count--)}),mm(i);var a=i[r];a||((a=i[r]={coordId:r,dataZoomInfos:{},count:0}).controller=function(t,e){var i=new rm(t.getZr());return C(["pan","zoom","scrollMove"],function(t){i.on(t,function(i){var n=[];C(e.dataZoomInfos,function(r){if(i.isAvailableBehavior(r.dataZoomModel.option)){var a=(r.getRange||{})[t],o=a&&a(e.controller,i);!r.dataZoomModel.get("disabled",!0)&&o&&n.push({dataZoomId:r.dataZoomId,start:o[0],end:o[1]})}}),n.length&&e.dispatchAction(n)})}),i}(t,a),a.dispatchAction=L(ym,t)),!a.dataZoomInfos[n]&&a.count++,a.dataZoomInfos[n]=e;var o,s,l,h,u=(o=a.dataZoomInfos,l={type_true:2,type_move:1,type_false:0,type_undefined:-1},h=!0,C(o,function(t){var e=t.dataZoomModel,i=!e.get("disabled",!0)&&(!e.get("zoomLock",!0)||"move");l["type_"+i]>l["type_"+s]&&(s=i),h&=e.get("preventDefaultMouseMove",!0)}),{controlType:s,opt:{zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!0,preventDefaultMouseMove:!!h}});a.controller.enable(u.controlType,u.opt),a.controller.setPointerChecker(e.containsPoint),vu(a,"dispatchAction",e.dataZoomModel.get("throttle",!0),"fixRate")}function gm(t){return t.type+"\0_"+t.id}function vm(t){var e=t.getZr();return e[fm]||(e[fm]={})}function mm(t){C(t,function(e,i){e.count||(e.controller.dispose(),delete t[i])})}function ym(t,e){t.dispatchAction({type:"dataZoom",batch:e})}var xm=P,_m=Hv.extend({type:"dataZoom.inside",init:function(t,e){this._range},render:function(t,e,i,n){_m.superApply(this,"render",arguments),this._range=t.getPercentRange(),C(this.getTargetCoordInfo(),function(e,n){var r=D(e,function(t){return gm(t.model)});C(e,function(e){var a=e.model,o={};C(["pan","zoom","scrollMove"],function(t){o[t]=xm(wm[t],this,e,n)},this),pm(i,{coordId:gm(a),allCoordIds:r,containsPoint:function(t,e,i){return a.coordinateSystem.containPoint([e,i])},dataZoomId:t.id,dataZoomModel:t,getRange:o})},this)},this)},dispose:function(){var t,e,i;t=this.api,e=this.dataZoomModel.id,C(i=vm(t),function(t){t.controller.dispose();var i=t.dataZoomInfos;i[e]&&(delete i[e],t.count--)}),mm(i),_m.superApply(this,"dispose",arguments),this._range=null}}),wm={zoom:function(t,e,i,n){var r=this._range,a=r.slice(),o=t.axisModels[0];if(o){var s=Mm[e](null,[n.originX,n.originY],o,i,t),l=(s.signal>0?s.pixelStart+s.pixelLength-s.pixel:s.pixel-s.pixelStart)/s.pixelLength*(a[1]-a[0])+a[0],h=Math.max(1/n.scale,0);a[0]=(a[0]-l)*h+l,a[1]=(a[1]-l)*h+l;var u=this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();return Gv(0,a,[0,100],0,u.minSpan,u.maxSpan),this._range=a,r[0]!==a[0]||r[1]!==a[1]?a:void 0}},pan:bm(function(t,e,i,n,r,a){var o=Mm[n]([a.oldX,a.oldY],[a.newX,a.newY],e,r,i);return o.signal*(t[1]-t[0])*o.pixel/o.pixelLength}),scrollMove:bm(function(t,e,i,n,r,a){return Mm[n]([0,0],[a.scrollDelta,a.scrollDelta],e,r,i).signal*(t[1]-t[0])*a.scrollDelta})};function bm(t){return function(e,i,n,r){var a=this._range,o=a.slice(),s=e.axisModels[0];if(s){var l=t(o,s,e,i,n,r);return Gv(l,o,[0,100],"all"),this._range=o,a[0]!==o[0]||a[1]!==o[1]?o:void 0}}}var Mm={grid:function(t,e,i,n,r){var a=i.axis,o={},s=r.model.coordinateSystem.getRect();return t=t||[0,0],"x"===a.dim?(o.pixel=e[0]-t[0],o.pixelLength=s.width,o.pixelStart=s.x,o.signal=a.inverse?1:-1):(o.pixel=e[1]-t[1],o.pixelLength=s.height,o.pixelStart=s.y,o.signal=a.inverse?-1:1),o},polar:function(t,e,i,n,r){var a=i.axis,o={},s=r.model.coordinateSystem,l=s.getRadiusAxis().getExtent(),h=s.getAngleAxis().getExtent();return t=t?s.pointToCoord(t):[0,0],e=s.pointToCoord(e),"radiusAxis"===i.mainType?(o.pixel=e[0]-t[0],o.pixelLength=l[1]-l[0],o.pixelStart=l[0],o.signal=a.inverse?1:-1):(o.pixel=e[1]-t[1],o.pixelLength=h[1]-h[0],o.pixelStart=h[0],o.signal=a.inverse?-1:1),o},singleAxis:function(t,e,i,n,r){var a=i.axis,o=r.model.coordinateSystem.getRect(),s={};return t=t||[0,0],"horizontal"===a.orient?(s.pixel=e[0]-t[0],s.pixelLength=o.width,s.pixelStart=o.x,s.signal=a.inverse?1:-1):(s.pixel=e[1]-t[1],s.pixelLength=o.height,s.pixelStart=o.y,s.signal=a.inverse?-1:1),s}};rd({getTargetSeries:function(t){var e=Q();return t.eachComponent("dataZoom",function(t){t.eachTargetAxis(function(t,i,n){C(n.getAxisProxy(t.name,i).getTargetSeriesModels(),function(t){e.set(t.uid,t)})})}),e},modifyOutputEnd:!0,overallReset:function(t,e){t.eachComponent("dataZoom",function(t){t.eachTargetAxis(function(t,i,n){n.getAxisProxy(t.name,i).reset(n,e)}),t.eachTargetAxis(function(t,i,n){n.getAxisProxy(t.name,i).filterData(n,e)})}),t.eachComponent("dataZoom",function(t){var e=t.findRepresentativeAxisProxy(),i=e.getDataPercentWindow(),n=e.getDataValueWindow();t.setRawRange({start:i[0],end:i[1],startValue:n[0],endValue:n[1]},!0)})}}),ad("dataZoom",function(t,e){var i=Lv(P(e.eachComponent,e,"dataZoom"),Pv,function(t,e){return t.get(e.axisIndex)}),n=[];e.eachComponent({mainType:"dataZoom",query:t},function(t,e){n.push.apply(n,i(t).nodes)}),C(n,function(e,i){e.setRawRange({start:t.start,end:t.end,startValue:t.startValue,endValue:t.endValue})})}),t.version="4.2.1",t.dependencies={zrender:"4.0.6"},t.PRIORITY=vc,t.init=function(t,e,i){var n=ed(t);if(n)return n;var r=new bc(t,e,i);return r.id="ec_"+$c++,qc[r.id]=r,vr(t,Qc,r.id),function(t){var e="__connectUpdateStatus";function i(t,i){for(var n=0;n
To make progress, we need better data on costs and performance to evaluate the - often simplistic and narrowly focused - solutions suggested. — Direction for ISO C++ [P0939R2]

1. Introduction

Error handling is never free. In C++, reacting to an error condition always bears some cost. It may be a speed cost from checks spread everywhere, or it may be a size cost for error handling cost, but costs are inevitable.

One may try to avoid all the costs by calling std::abort or something similar, but even that has costs. The only cost-free option is to ignore the errors entirely and expose yourself to the wrath of UB.

So great, there are costs, but how should we measure the costs, and which error handling mechanisms exhibit what kinds of costs?

In this paper, we will look at the size costs of error handling. We’ll break things down into one-time costs and incremental costs, and subdivide by costs paid for error neutral functions, raising an error, and handling an error. I will also discuss some of the inherent implementation difficulties and constraints of today’s C++ exceptions.

2. Exception implementation

In GCC, Clang, and MSVC x64, exceptions are implemented using the "table-based exceptions" strategy. When an exception is thrown, the instruction pointer is used to look in a constant, global table to determine how to restore registers, which destructors to call, and how to get to the next frame. This approach has the advantage that minimal extra code is required to be executed in the success path.

In MSVC x86, exceptions are implemented with a variant of the "setjmp/longjmp" method. Bookkeeping information is emitted anytime a try block is entered, or anytime an object with a non-trivial destructor has been constructed. This information is linked together into a list. When an exception is thrown, the list is traversed, destructors and catch blocks are executed. This approach has the advantage that throwing an exception has a much more predictable and consistent cost than the table-based approach.

In libc++abi (usually associated with Clang) and libsupc++ (usually associated with GCC), exception objects are allocated on the heap. Both implementations have an emergency buffer they fall back to if allocations fail. An alternative implementation could use the fixed sized buffer first, though this would still qualify as a dynamic allocation.

With MSVC, exception objects are allocated into a buffer that is borrowed from the stack just beyond the throw site’s active frame. Each active exception gets a distinct buffer. The exception buffer and the stack frames between the throw and catch sites cannot be deallocated or reused until the exception is fully handled. Destructors and other code run during unwinding consumes additional stack beyond the throwing stack frame and exception buffer. At minimum, throwing one exception consumes roughly 2,100 bytes of stack on 32-bit Windows, and 9,700 bytes of stack on 64-bit Windows. The stack size cost will quickly increase with large exception types, re-throws, distance between the throw and catch sites, and/or multiple active exceptions.

The heap is often not present in freestanding environments. Stack space is often tightly constrained in freestanding environments as well.

[RenwickLowCost] describes a way to implement exceptions by passing in exception information though a hidden function parameter. Currently, this approach can’t be used for a conforming C++ implementation, but it will come close enough for many applications. Most of the "tricky use cases" outlined below are not implementable with the hidden parameter trick unless all functions, including noexcept and C functions, are all passed the hidden parameter. This would significantly undermine the utility of the approach. The author does not have access to a compiler with this implementation of exceptions, so it has not been benchmarked.

[P0709] describes a way to implement a new kind of exceptions, where the error information is packaged with the return value in a discriminated union. The author does not have access to a compiler that can use this kind of exception handling mechanism, so it has not been benchmarked. Readers should _not_ assume that the costs will be the same as those for expected or returning a struct, as the code to test and the code to set the discriminator could cause substantial size differences from what was measured for existing cases. The benefits of this approach are realized when a specific type (a yet to be standardized std::error) is thrown. Throwing other types falls back to the current C++ exception approach.

Conforming C++ exceptions need to be able to support some tricky use cases.

  • Transporting information across noexcept barriers.

  • uncaught_exceptions()

  • current_exception()

  • Re-throwing exceptions in distant functions, for example, in a "Lippincott" function [Guillemot].

  • Multiple in-flight exceptions at the same time.

In addition, for exceptions to be acceptable in the market, there is also the requirement that C++ programs should be able to consume C source and C object files.

In general, supporting these difficult use cases requires some kind of storage that is local to a thread. In single threaded environments, "storage that is local to a thread" can be implemented with a simple global. In multi-threaded environments, something more invasive or sophisticated is required. In practice, the "more invasive or sophisticated" facilities are often not available in freestanding environments. Getting those features into freestanding environments often requires substantial runtime cost, cooperation from vendors other than the compiler vendor, or both runtime cost and vendor cooperation.

It may be possible to support useful, but non-conforming exceptions in freestanding environments. This paper should help quantify some of the size costs. The larger the size cost, the less utility the facility provides.

3. Measuring methodology

All benchmarks lie. It’s important to know how a benchmark is set up so that the useful parts can be distinguished from the misleading parts.

The specific build flags can be found in Appendix B. Following is a brief summary.

MSVC 2019 was used for MSVC x86 and MSVC x64 builds. The /d2FH4 flag described in [MoFH4] was used, and /EHs was used when exceptions were on.

GCC 7.3.1 from the Red Hat Developer Toolset 7.1 was used for my GCC builds. The Linux x64 platform was targeted.

Clang 8.0.0, libc++, and libc++abi was used for my Clang builds. The Linux x64 platform was targeted. The system linker and C library leaked in to this build. The system GCC was GCC 4.8.4 from Ubuntu 14.04.3.

All the binaries are optimized for size, rather than speed.

All the binaries are built with static runtimes, so that we can also see the costs of the error handling runtime machinery. For many people, this is a sunk cost. If the cost of the runtime machinery isn’t of interest, then don’t pay attention to the one-time costs, and just look at the incremental costs. Sizes were not calculated by just doing the "easy" thing and comparing the on-disk sizes of the resulting programs. Programs have lots and lots of padding internal to them due to alignment constraints, and that padding can mask or inflate small cost changes. Instead, the size is calculated by summing the size of all the non-code sections, and by summing the size of each function in the code sections. Measuring the size of a function is a little tricky, as the compiler doesn’t emit that information directly. There are often padding instructions between consecutive functions. My measurements omit the padding instructions so that we can see code size differences as small as one byte.

Measurements are also included where the size of some data sections related to unwinding are omitted. On x64 Linux, programs can have an .eh_frame and .eh_frame_hdr section that can help with emitting back traces. x64 Windows has similar sections named .xdata and .pdata. These sections aren’t sufficient to implement C++ exception handling, and they don’t go away when exceptions are turned off. On Linux and Windows, these sections should be considered a sunk cost, but on more exotic platforms, it is reasonable to omit those sections, as stack trace costs may not be tolerable. These measurements are all labeled as "stripped". x86 Windows doesn’t have these sections, so the "stripped" measurements are the same as the unstripped measurements.

Note that on Linux, the entire user mode program can be statically linked. This is the program under test, the C++ runtime, the C runtime, and any OS support. On Windows, the program, the C++ runtime, and the C runtime can be statically linked, but the OS support (kernel32.dll) is still distinct. With this in mind, refrain from comparing the one-time MSVC sizes to the Clang and GCC sizes, as it isn’t comparing the same set of functionality.

These benchmarks are run on very small programs. On larger programs, various code and data deduplication optimizations could substantially change the application-level costs of error handling. [MoFH4] documents the kinds of deduplication that MSVC 2019 performs.

4. Starter test cases

To start with, we will look at code similar to the following:
struct Dtor {~Dtor() {}};
int global_int = 0;
void callee() {/* will raise an error one day*/}
void caller() {
  Dtor d;
  callee();
  global_int = 0;
}
int main() { 
  caller();
  return global_int;
}
This code has some important properties for future comparisons.
  • callee() will eventually raise errors.

  • caller() needs to clean up the d object in error and non-error conditions.

  • caller() should only set global_int in success cases.

  • The code doesn’t have any error cases yet. We can see the cost of error handling machinery when no errors are involved.

In the actual tests all the function bodies are in separate .cpp files, and link-time / whole-program optimizations aren’t used. If they had been used, the entire program would get optimized away, removing our ability to measure error handling differences.

The above program is a useful template when using exceptions or std::abort as an error handling mechanism, but it won’t work as well for error codes. So we mutate the program like so...

int callee() {return 0;}
int caller() {
  Dtor d;
  int e = callee();
  if (e)
    return e;
  global_int = 0;
  return e;
}
This is pretty typical integer return value code, without any macro niceties.

Most of the programs were built with exceptions turned off, but the throw_* cases and noexcept_abort all had exceptions turned on in the program.

  • abort: When an error is encountered, kill the program with std::abort.

  • noexcept_abort: Same as abort, except exceptions are turned on, and all the functions declared in user source are marked as noexcept.

  • return_val: Return an integer error code, where zero represents success.

  • return_struct: Return an error_struct object (described below) rather than an integer error code.

  • ref_val and ref_struct: Rather than returning integers and error_structs, construct them in main and pass them in by mutable reference.

  • expected_val and expected_struct: Use tl::expected [BrandExpected] wrapping either an integer or an error_struct, accordingly.

  • outcome_val and outcome_struct: Use outcome::experimental::status_result [DouglasOutcome] wrapping either an integer or an error_struct, accordingly. This is built with RTTI turned off.

  • outcome_std_error: Use outcome::experimental::status_result [DouglasOutcome] wrapping a prototype of the proposed std::error [P1028R1]. This is the idiomatic way to use outcome. This is built with RTTI turned off.

  • tls_val and tls_struct: Use thread_local variables to communicate error conditions.

  • throw_val and throw_struct: Throw an integer or error_struct as an exception. This is to allow a direct comparison to the other error handling strategies in terms of information transmitted from error site to handling site.

  • throw_exception: Throw an exception deriving from std::exception, that contains only an int. This should represent more typical use cases.

Expository code for all the cases can be found in Appendix C. The actual code used for the benchmark can be found on my github.

5. Measurements

5.1. Initial error neutral size cost

My first batch of measurements is comparing each of the mechanisms to the abort test case that has no unwind information. This lets us focus on the incremental costs of the other mechanisms.

Warning! Logarithmic axis! Linear version here

Warning! Logarithmic axis! Linear version here

Set aside outcome for a moment. These tables show us that the one-time cost for exceptions is really high (6KB on MSVC x86, 382KB on Clang x64), and the one time cost for unwind information is pretty high too (6KB on MSVC x64, 57KB on Clang). Once we ignore unwind information, we can see that the one-time cost for TLS on Windows is small compared to unwind information, but high compared to the other error mechanisms (214 bytes - 481 bytes). All the other (non-outcome) one-time overheads are 66 bytes or less. Remember that this code doesn’t currently have any throw statements in the program. This is the one-time cost of error neutral functions when exceptions are turned on.

On MSVC, outcome pulls in exception handling routines, even though exceptions are disabled.

[BatyievEmbedded] claims to be able to get the cost of the exception machinery down to 6,760 bytes on a bare metal ARMv4t system in Thumb mode with GCC 5.3.0.

Note that noexcept_abort has the same cost as regular abort right now. If everything is noexcept, the exception machinery costs are not incurred.

5.2. Incremental error neutral size cost

To measure the incremental cost of error neutral code, the code will be updated as follows:
void callee2(int amount) {
  global_int += amount;
  // will error one day
}
void caller2(int amount) {
  Dtor d;