c++11以后的那些语法糖并不能带来程序性能的提升

本文通过对比测试,评估了C++11引入的语法糖如tuple、for_each和lambda表达式在函数返回值及vector遍历操作中的实际性能表现。

一 需求:

c++11后有些让人看着很炫的语法糖,比如tuple,for_each等,但是它们并不能提升c++程序性能,做个简单测试,验证这些语法糖带来的效果。

二 实现:

1.测试函数返回多个值

(1)使用tuple返回

   (2) 使用结构体引用返回

2.测试遍历一个vector,并对其中元素执行操作

   (1) 使用普通循环

   (2) 使用for (auto &e : v)

   (3) 使用for_each和lamba表达式

三 测试代码

1.test.cpp

#include <iostream>
#include <string>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
template <typename T, auto value> 
T foo(T a) {
	return a + value;
}
tuple<int, double, string>f() {
	return make_tuple(1, 1.00, "123");
}
struct T {
	int a;
	double b;
	string c;
};
void f(T &t) {
	t.a = 1;
	t.b = 1.00;
	t.c = "123";
}
void f0(const vector<string>&v) {
	int size = v.size();
	string str;
	for (int i = 0;i < size;i++) {
		str = v[i];
	}
}
void f1(const vector<string>&v) {
	string str;
	for (auto &e : v) {
        str = e;
    }
}
void f2(const vector<string>&v) {
    string str;
    for_each(begin(v), end(v), [&str] (auto e) {
			str = e;
			});
}


int main() {
//	cout << foo<double, 10>(12.0) << endl;
	T t;
	vector<string>v{"123", "1212", "hello world", "c++ world", "fun work"};
	for (int i = 0;i < 1000000;i++) {
//		auto [x, y, z] = f();	// 0.254s
//		f(t);					// 0.117s
//		f0(v);					// 0.330s
//		f1(v);					// 0.368s
		f2(v);					// 0.792s
	}
/*	cout << x << endl;
	cout << y << endl;
	cout << z << endl;*/

    return 0;
}

2.make.sh

g++ -std=c++17 -g -o Test test.cpp -pthread

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值