Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C++11 modernization — use emplace_back for performance #1046

Merged
merged 2 commits into from Feb 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .clang-tidy
@@ -1,5 +1,5 @@
---
Checks: '-*,readability-*,bugprone-*,misc-*,performance-*,modernize-redundant-void-arg,modernize-deprecated-headers,modernize-use-override,modernize-use-auto,modernize-use-nullptr,modernize-use-default-member-init,modernize-use-equals-default,modernize-use-equals-delete,modernize-pass-by-value,modernize-loop-convert,modernize-raw-string-literal,modernize-use-noexcept,modernize-return-braced-init-list,-readability-else-after-return,-readability-named-parameter,-readability-braces-around-statements,-readability-inconsistent-declaration-parameter-name,-readability-isolate-declaration,-readability-magic-numbers,-readability-convert-member-functions-to-static,-bugprone-macro-parentheses,-bugprone-narrowing-conversions,-bugprone-branch-clone,-misc-non-private-member-variables-in-classes,-misc-unused-parameters'
Checks: '-*,readability-*,bugprone-*,misc-*,performance-*,modernize-redundant-void-arg,modernize-deprecated-headers,modernize-use-override,modernize-use-auto,modernize-use-nullptr,modernize-use-default-member-init,modernize-use-equals-default,modernize-use-equals-delete,modernize-pass-by-value,modernize-loop-convert,modernize-raw-string-literal,modernize-use-noexcept,modernize-return-braced-init-list,modernize-use-emplace,-readability-else-after-return,-readability-named-parameter,-readability-braces-around-statements,-readability-inconsistent-declaration-parameter-name,-readability-isolate-declaration,-readability-magic-numbers,-readability-convert-member-functions-to-static,-bugprone-macro-parentheses,-bugprone-narrowing-conversions,-bugprone-branch-clone,-misc-non-private-member-variables-in-classes,-misc-unused-parameters'
WarningsAsErrors: ''
HeaderFilterRegex: '.*'
AnalyzeTemporaryDtors: false
Expand Down
26 changes: 13 additions & 13 deletions Examples/BasketLosses/BasketLosses.cpp
Expand Up @@ -78,8 +78,8 @@ int main(int, char* []) {
boost::lexical_cast<std::string>(i));
std::vector<Handle<DefaultProbabilityTermStructure> > defTS;
for (double& hazardRate : hazardRates) {
defTS.push_back(Handle<DefaultProbabilityTermStructure>(
ext::make_shared<FlatHazardRate>(0, TARGET(), hazardRate, Actual365Fixed())));
defTS.emplace_back(
ext::make_shared<FlatHazardRate>(0, TARGET(), hazardRate, Actual365Fixed()));
defTS.back()->enableExtrapolation();
}
std::vector<Issuer> issuers;
Expand All @@ -89,7 +89,7 @@ int main(int, char* []) {
EURCurrency(), QuantLib::SeniorSec,
Period(), 1. // amount threshold
), defTS[i]));
issuers.push_back(Issuer(curves));
issuers.emplace_back(curves);
}

ext::shared_ptr<Pool> thePool = ext::make_shared<Pool>();
Expand Down Expand Up @@ -247,28 +247,28 @@ int main(int, char* []) {

// Base Correlation model set up to test cocherence with base LHP model
std::vector<Period> bcTenors;
bcTenors.push_back(Period(1, Years));
bcTenors.push_back(Period(5, Years));
bcTenors.emplace_back(1, Years);
bcTenors.emplace_back(5, Years);
std::vector<Real> bcLossPercentages;
bcLossPercentages.push_back(0.03);
bcLossPercentages.push_back(0.12);
std::vector<std::vector<Handle<Quote> > > correls;
//
std::vector<Handle<Quote> > corr1Y;
// 3%
corr1Y.push_back(Handle<Quote>(ext::shared_ptr<Quote>(
new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0]))));
corr1Y.emplace_back(
ext::shared_ptr<Quote>(new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0])));
// 12%
corr1Y.push_back(Handle<Quote>(ext::shared_ptr<Quote>(
new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0]))));
corr1Y.emplace_back(
ext::shared_ptr<Quote>(new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0])));
correls.push_back(corr1Y);
std::vector<Handle<Quote> > corr2Y;
// 3%
corr2Y.push_back(Handle<Quote>(ext::shared_ptr<Quote>(
new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0]))));
corr2Y.emplace_back(
ext::shared_ptr<Quote>(new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0])));
// 12%
corr2Y.push_back(Handle<Quote>(ext::shared_ptr<Quote>(
new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0]))));
corr2Y.emplace_back(
ext::shared_ptr<Quote>(new SimpleQuote(fctrsWeights[0][0] * fctrsWeights[0][0])));
correls.push_back(corr2Y);
ext::shared_ptr<BaseCorrelationTermStructure<BilinearInterpolation> >
correlSurface(
Expand Down
10 changes: 5 additions & 5 deletions Examples/BermudanSwaption/BermudanSwaption.cpp
Expand Up @@ -166,11 +166,11 @@ int main(int, char* []) {

// defining the swaptions to be used in model calibration
std::vector<Period> swaptionMaturities;
swaptionMaturities.push_back(Period(1, Years));
swaptionMaturities.push_back(Period(2, Years));
swaptionMaturities.push_back(Period(3, Years));
swaptionMaturities.push_back(Period(4, Years));
swaptionMaturities.push_back(Period(5, Years));
swaptionMaturities.emplace_back(1, Years);
swaptionMaturities.emplace_back(2, Years);
swaptionMaturities.emplace_back(3, Years);
swaptionMaturities.emplace_back(4, Years);
swaptionMaturities.emplace_back(5, Years);

std::vector<ext::shared_ptr<BlackCalibrationHelper> > swaptions;

Expand Down
30 changes: 9 additions & 21 deletions Examples/CVAIRS/CVAIRS.cpp
Expand Up @@ -123,27 +123,15 @@ int main(int, char* []) {
intesitiesVHigh.push_back(intensitiesHigh[i]);
}

defaultIntensityTS.push_back(Handle<DefaultProbabilityTermStructure>(
ext::shared_ptr<DefaultProbabilityTermStructure>(
new InterpolatedHazardRateCurve<BackwardFlat>(
defaultTSDates,
intesitiesVLow,
Actual360(),
TARGET()))));
defaultIntensityTS.push_back(Handle<DefaultProbabilityTermStructure>(
ext::shared_ptr<DefaultProbabilityTermStructure>(
new InterpolatedHazardRateCurve<BackwardFlat>(
defaultTSDates,
intesitiesVMedium,
Actual360(),
TARGET()))));
defaultIntensityTS.push_back(Handle<DefaultProbabilityTermStructure>(
ext::shared_ptr<DefaultProbabilityTermStructure>(
new InterpolatedHazardRateCurve<BackwardFlat>(
defaultTSDates,
intesitiesVHigh,
Actual360(),
TARGET()))));
defaultIntensityTS.emplace_back(ext::shared_ptr<DefaultProbabilityTermStructure>(
new InterpolatedHazardRateCurve<BackwardFlat>(defaultTSDates, intesitiesVLow,
Actual360(), TARGET())));
defaultIntensityTS.emplace_back(ext::shared_ptr<DefaultProbabilityTermStructure>(
new InterpolatedHazardRateCurve<BackwardFlat>(defaultTSDates, intesitiesVMedium,
Actual360(), TARGET())));
defaultIntensityTS.emplace_back(ext::shared_ptr<DefaultProbabilityTermStructure>(
new InterpolatedHazardRateCurve<BackwardFlat>(defaultTSDates, intesitiesVHigh,
Actual360(), TARGET())));

Volatility blackVol = 0.15;
ext::shared_ptr<PricingEngine> ctptySwapCvaLow =
Expand Down
6 changes: 3 additions & 3 deletions Examples/LatentModel/LatentModel.cpp
Expand Up @@ -73,16 +73,16 @@ int main(int, char* []) {
std::vector<Handle<DefaultProbabilityTermStructure> > defTS;
defTS.reserve(hazardRates.size());
for (double& hazardRate : hazardRates)
defTS.push_back(Handle<DefaultProbabilityTermStructure>(
ext::make_shared<FlatHazardRate>(0, TARGET(), hazardRate, Actual365Fixed())));
defTS.emplace_back(
ext::make_shared<FlatHazardRate>(0, TARGET(), hazardRate, Actual365Fixed()));
std::vector<Issuer> issuers;
for(Size i=0; i<hazardRates.size(); i++) {
std::vector<QuantLib::Issuer::key_curve_pair> curves(1,
std::make_pair(NorthAmericaCorpDefaultKey(
EURCurrency(), QuantLib::SeniorSec,
Period(), 1. // amount threshold
), defTS[i]));
issuers.push_back(Issuer(curves));
issuers.emplace_back(curves);
}

ext::shared_ptr<Pool> thePool = ext::make_shared<Pool>();
Expand Down
2 changes: 1 addition & 1 deletion ql/cashflows/couponpricer.cpp
Expand Up @@ -331,7 +331,7 @@ namespace QuantLib {
std::vector<PricerSetter> setter;
setter.reserve(p.size());
for (const auto& i : p) {
setter.push_back(PricerSetter(i));
setter.emplace_back(i);
}
for (const auto& i : leg) {
Size j = 0;
Expand Down
2 changes: 1 addition & 1 deletion ql/experimental/catbonds/catrisk.cpp
Expand Up @@ -110,7 +110,7 @@ namespace QuantLib {
Date eventDate = start_ + days*Days;
if(eventDate<=end_)
{
path.push_back(std::pair<Date, Real> (eventDate, generateBeta()));
path.emplace_back(eventDate, generateBeta());
}
else break;
eventFraction = exponential_();
Expand Down
4 changes: 2 additions & 2 deletions ql/experimental/catbonds/riskynotional.cpp
Expand Up @@ -24,7 +24,7 @@ namespace QuantLib
NotionalPath::NotionalPath()
{
Rate previous = 1.0;//full notional at the beginning
notionalRate_.push_back(std::pair<Date, Real>(Date(), previous));
notionalRate_.emplace_back(Date(), previous);
}

Rate NotionalPath::notionalRate(const Date& date) const
Expand All @@ -40,7 +40,7 @@ namespace QuantLib
}

void NotionalPath::addReduction(const Date &date, Rate newRate) {
notionalRate_.push_back(std::pair<Date, Real>(date, newRate));
notionalRate_.emplace_back(date, newRate);
}

Real NotionalPath::loss() {
Expand Down
6 changes: 2 additions & 4 deletions ql/experimental/credit/gaussianlhplossmodel.cpp
Expand Up @@ -61,8 +61,7 @@ namespace QuantLib {
biphi_(-sqrt(correlation))
{
for (double recoverie : recoveries)
rrQuotes_.push_back(
Handle<RecoveryRateQuote>(ext::make_shared<RecoveryRateQuote>(recoverie)));
rrQuotes_.emplace_back(ext::make_shared<RecoveryRateQuote>(recoverie));
}

GaussianLHPLossModel::GaussianLHPLossModel(
Expand All @@ -79,8 +78,7 @@ namespace QuantLib {
{
registerWith(correl_);
for (double recoverie : recoveries)
rrQuotes_.push_back(
Handle<RecoveryRateQuote>(ext::make_shared<RecoveryRateQuote>(recoverie)));
rrQuotes_.emplace_back(ext::make_shared<RecoveryRateQuote>(recoverie));
}


Expand Down
2 changes: 1 addition & 1 deletion ql/experimental/credit/issuer.cpp
Expand Up @@ -52,7 +52,7 @@ namespace QuantLib {
for(Size i=0; i <eventTypes.size(); i++) {
DefaultProbKey keytmp(eventTypes[i], currencies[i],
seniorities[i]);
probabilities_.push_back(std::make_pair(keytmp, curves[i]));
probabilities_.emplace_back(keytmp, curves[i]);
}
}

Expand Down
8 changes: 4 additions & 4 deletions ql/experimental/math/fireflyalgorithm.cpp
Expand Up @@ -55,16 +55,16 @@ namespace QuantLib {
//Prepare containers
for (Size i = 0; i < M_; i++) {
const SobolRsg::sample_type::value_type &sample = sobol.nextSequence().value;
x_.push_back(Array(N_, 0.0));
xI_.push_back(Array(N_, 0.0));
xRW_.push_back(Array(N_, 0.0));
x_.emplace_back(N_, 0.0);
xI_.emplace_back(N_, 0.0);
xRW_.emplace_back(N_, 0.0);
Array& x = x_.back();
for (Size j = 0; j < N_; j++) {
//Assign X=lb+(ub-lb)*random
x[j] = lX_[j] + bounds[j] * sample[j];
}
//Evaluate point
values_.push_back(std::make_pair(P.value(x), i));
values_.emplace_back(P.value(x), i);
}

//init intensity & randomWalk
Expand Down
2 changes: 1 addition & 1 deletion ql/experimental/math/latentmodel.hpp
Expand Up @@ -686,7 +686,7 @@ namespace QuantLib {
nVariables_(factorWeights.size())
{
for (double factorWeight : factorWeights)
factorWeights_.push_back(std::vector<Real>(1, factorWeight));
factorWeights_.emplace_back(1, factorWeight);
for (double factorWeight : factorWeights)
idiosyncFctrs_.push_back(std::sqrt(1. - factorWeight * factorWeight));
//convert row to column vector....
Expand Down
6 changes: 3 additions & 3 deletions ql/experimental/math/particleswarmoptimization.cpp
Expand Up @@ -71,11 +71,11 @@ namespace QuantLib {
//Prepare containers
for (Size i = 0; i < M_; i++) {
const SobolRsg::sample_type::value_type &sample = sobol.nextSequence().value;
X_.push_back(Array(N_, 0.0));
X_.emplace_back(N_, 0.0);
Array& x = X_.back();
V_.push_back(Array(N_, 0.0));
V_.emplace_back(N_, 0.0);
Array& v = V_.back();
gBX_.push_back(Array(N_, 0.0));
gBX_.emplace_back(N_, 0.0);
for (Size j = 0; j < N_; j++) {
//Assign X=lb+(ub-lb)*random
x[j] = lX_[j] + bounds[j] * sample[2 * j];
Expand Down
9 changes: 3 additions & 6 deletions ql/experimental/math/tcopulapolicy.cpp
Expand Up @@ -32,7 +32,7 @@ namespace QuantLib {
// require no T is of order 2 (finite variance)
QL_REQUIRE(tOrder > 2, "Non finite variance T in latent model.");

distributions_.push_back(boost::math::students_t_distribution<>(tOrder));
distributions_.emplace_back(tOrder);
// inverses T variaces used in normalization of the random factors
// For low values of the T order this number is very close to zero
// and it enters the expressions dividing them, which introduces
Expand All @@ -58,11 +58,8 @@ namespace QuantLib {
normFactorWeights.push_back(factorWeight[iFactor] * varianceFactors_[iFactor]);
// idiosincratic term, all Z factors are assumed identical.
normFactorWeights.push_back(idiosyncFctr * varianceFactors_.back());
latentVarsCumul_.push_back(
CumulativeBehrensFisher(vals.tOrders, normFactorWeights));
latentVarsInverters_.push_back(
InverseCumulativeBehrensFisher(vals.tOrders,
normFactorWeights));
latentVarsCumul_.emplace_back(vals.tOrders, normFactorWeights);
latentVarsInverters_.emplace_back(vals.tOrders, normFactorWeights);
}
}

Expand Down
5 changes: 2 additions & 3 deletions ql/experimental/models/normalclvmodel.cpp
Expand Up @@ -111,9 +111,8 @@ namespace QuantLib {
}

for (Size i=0; i < data_->s_.rows(); ++i) {
data_->interpl_.push_back(
LinearInterpolation(data_->t_.begin(), data_->t_.end(),
data_->s_.row_begin(i)));
data_->interpl_.emplace_back(data_->t_.begin(), data_->t_.end(),
data_->s_.row_begin(i));
}
}

Expand Down
2 changes: 1 addition & 1 deletion ql/instruments/bond.cpp
Expand Up @@ -366,7 +366,7 @@ namespace QuantLib {
notionals_.clear();

Date lastPaymentDate = Date();
notionalSchedule_.push_back(Date());
notionalSchedule_.emplace_back();
for (auto& cashflow : cashflows_) {
ext::shared_ptr<Coupon> coupon = ext::dynamic_pointer_cast<Coupon>(cashflow);
if (!coupon)
Expand Down
2 changes: 1 addition & 1 deletion ql/instruments/compositeinstrument.cpp
Expand Up @@ -23,7 +23,7 @@ namespace QuantLib {

void CompositeInstrument::add(
const ext::shared_ptr<Instrument>& instrument, Real multiplier) {
components_.push_back(std::make_pair(instrument,multiplier));
components_.emplace_back(instrument, multiplier);
registerWith(instrument);
update();
// When we ask for the NPV of an expired composite, the
Expand Down
2 changes: 1 addition & 1 deletion ql/math/matrixutilities/gmres.cpp
Expand Up @@ -88,7 +88,7 @@ namespace QuantLib {
std::list<Real> errors(1, g/bn);

for (Size j=0; j < maxIter_ && errors.back() >= relTol_; ++j) {
h.push_back(Array(maxIter_, 0.0));
h.emplace_back(maxIter_, 0.0);
Array w = A_(M_ == QL_NULL_FUNCTION ? v[j] : M_(v[j]));

for (Size i=0; i <= j; ++i) {
Expand Down
10 changes: 5 additions & 5 deletions ql/math/pascaltriangle.cpp
Expand Up @@ -28,12 +28,12 @@ namespace QuantLib {
const std::vector<BigNatural>& PascalTriangle::get(Size order) {
if (coefficients_.empty()) {
// order zero mandatory for bootstrap
coefficients_.push_back(std::vector<BigNatural>(1, 1));
coefficients_.emplace_back(1, 1);

coefficients_.push_back(std::vector<BigNatural>(2, 1));
coefficients_.push_back(std::vector<BigNatural>(3, 1));
coefficients_.emplace_back(2, 1);
coefficients_.emplace_back(3, 1);
coefficients_[2][1] = 2;
coefficients_.push_back(std::vector<BigNatural>(4, 1));
coefficients_.emplace_back(4, 1);
coefficients_[3][1] = coefficients_[3][2] = 3;
}
while (coefficients_.size()<=order)
Expand All @@ -43,7 +43,7 @@ namespace QuantLib {

void PascalTriangle::nextOrder() {
Size order = coefficients_.size();
coefficients_.push_back(std::vector<BigNatural>(order+1));
coefficients_.emplace_back(order + 1);
coefficients_[order][0] = coefficients_[order][order] = 1;
for (Size i=1; i<order/2+1; ++i) {
coefficients_[order][i] = coefficients_[order][order-i] =
Expand Down
2 changes: 1 addition & 1 deletion ql/math/statistics/generalstatistics.hpp
Expand Up @@ -222,7 +222,7 @@ namespace QuantLib {
/*! \pre weights must be positive or null */
inline void GeneralStatistics::add(Real value, Real weight) {
QL_REQUIRE(weight>=0.0, "negative weight not allowed");
samples_.push_back(std::make_pair(value,weight));
samples_.emplace_back(value, weight);
sorted_ = false;
}

Expand Down
Expand Up @@ -209,10 +209,10 @@ namespace QuantLib {
odeSolution, _1, true), points[i]),
QL_EPSILON, x[j], 0.5/size);

w.push_back(std::make_pair(std::min(x[size-2], x[j]), e));
w.emplace_back(std::min(x[size - 2], x[j]), e);
}
}
w.push_back(std::make_pair(1.0, 1.0));
w.emplace_back(1.0, 1.0);
std::sort(w.begin(), w.end());
w.erase(std::unique(w.begin(), w.end(), equal_on_first), w.end());

Expand Down
Expand Up @@ -52,13 +52,12 @@ namespace QuantLib {
for (const auto& i : dividendSchedule) {
const Time t = process->time(i->date());
if (t <= maturity && t >= 0.0)
intermediateSteps.push_back(std::make_pair(process->time(i->date()), i->amount()));
intermediateSteps.emplace_back(process->time(i->date()), i->amount());
}

const Size intermediateTimeSteps = std::max<Size>(2, Size(24.0*maturity));
for (Size i=0; i < intermediateTimeSteps; ++i)
intermediateSteps.push_back(
std::make_pair((i+1)*(maturity/intermediateTimeSteps), 0.0));
intermediateSteps.emplace_back((i + 1) * (maturity / intermediateTimeSteps), 0.0);

std::sort(intermediateSteps.begin(), intermediateSteps.end());

Expand Down
Expand Up @@ -67,7 +67,7 @@ namespace QuantLib {

std::list<std::vector<Time> > stoppingTimes;
stoppingTimes.push_back(c2->stoppingTimes());
stoppingTimes.push_back(std::vector<Time>(1, c1->getTime()));
stoppingTimes.emplace_back(1, c1->getTime());

FdmStepConditionComposite::Conditions conditions;
conditions.push_back(c2);
Expand Down
2 changes: 1 addition & 1 deletion ql/models/marketmodels/accountingengine.cpp
Expand Up @@ -44,7 +44,7 @@ namespace QuantLib {
const std::vector<Rate>& rateTimes = product_->evolution().rateTimes();
discounters_.reserve(cashFlowTimes.size());
for (double cashFlowTime : cashFlowTimes)
discounters_.push_back(MarketModelDiscounter(cashFlowTime, rateTimes));
discounters_.emplace_back(cashFlowTime, rateTimes);
}

Real AccountingEngine::singlePathValues(std::vector<Real>& values) {
Expand Down