SlideShare a Scribd company logo
C++ vs Go
Go Language Evangelism
Language complains
• There is no way to centralize error handling, and you
doing it the “old good way” (check after each step):
No exceptions
defer ts.Close()
conf := newConf(ts.URL)
_, err := conf.Exchange(context.Background(), "exchange-
code")
if err == nil {
t.Fatalf("got no error, expected one")
}
_, ok := err.(*RetrieveError)
if !ok {
t.Fatalf("got %T error, expected *RetrieveError; error
was: %v", err, err)
•So observations are that average Go
function length might be up to 3x
longer if to correctly handle all
errors (than comparable C*/C++
code)
No exceptions
* C at least has a preprocessor
•"If it walks like a duck and it quacks like a
duck, then it must be a duck”
•In duck typing, an object's suitability is
determined by the presence of
certain methods and properties, rather than
the type of the object itself.
Duck Typing vs True
https://en.wikipedia.org/wiki/Duck_typing
type Reader struct {
    r io.ReaderAt
    File []*File
    Comment string
    decompressors map[uint16]Decompressor
}

...

func (z *Reader) init(r io.ReaderAt, size int64) error {
    end, err := readDirectoryEnd(r, size)
    if err != nil {
        return err
    }
    ...
}
...
func (z *Reader) RegisterDecompressor(method uint16, dcomp
Decompressor) {
    if z.decompressors == nil {
        z.decompressors = make(map[uint16]Decompressor)
    }
    z.decompressors[method] = dcomp
}
UglyClasses
type Reader struct {
    r io.ReaderAt
    File []*File
    Comment string
    decompressors map[uint16]Decompressor
}

...

func (z *Reader) init(r io.ReaderAt, size int64) error {
    end, err := readDirectoryEnd(r, size)
    if err != nil {
        return err
    }
    ...
}
...
func (z *Reader) RegisterDecompressor(method uint16, dcomp
Decompressor) {
    if z.decompressors == nil {
        z.decompressors = make(map[uint16]Decompressor)
    }
    z.decompressors[method] = dcomp
}
UglyClasses
MODULE Lists;
TYPE
List* = POINTER TO ListNode;
ListNode = RECORD
value : Integer;
next : List;
END;
PROCEDURE (l : List) Add* (v : Integer);
BEGIN
IF l = NIL THEN
NEW(l); (* create record instance *)
l.value := v
ELSE
l.next.Add(v) (* recursive call to .add(n) *)
END
END Add;
Oberon-2
UglyClasses
LL(1) grammar with C-like keywords
var prohibitionaryDialArgTests =
[]struct {
network string
address string
}{
{"tcp4", "127.0.0.1"},
{"tcp6", "::ffff:127.0.0.1"},
}
func DoProhibitionaryDialArg(t
*testing.T) (error) {
Go
const
prohibitionaryDialArgTests : array [1..2]
of record
network : string;
address : string;
end = (
(network: ‘tcp4’, address:
‘127.0.0.1’),
(network: ‘tcp6’, address: ‘::ffff:
127.0.0.1’)
);
function DoProhibitionaryDialArg(var t:
Testing.T) : TError;

Pascal
Pascal/Oberon syntax which mimics C
•Order of keywords in declaration
•No name overloads
• No generics
• No pointer arithmetic
• Fast compiler
• Weak optimizer
• Source modules-based build
• blahblahthousandsmoreweakanalogues
More Pascal/Oberon like…
Containers anyone?
C++ Go
std::vector<int> vector;
vector[i]
vector := []int{}
vector[i]
std::stack<int> stack; stack := []int{}
stack.push(value); stack = append(stack, value)
value = stack.top();
stack.pop()
stack, value = stack[:len(stack)-1],
stack[len(stack)-1]
std::deque<int> q{};
q.push_back(value);
q.pop_front();
import "github.com/gammazero/deque”
func (q *Deque) PushBack(elem
interface{})
func (q *Deque) PopBack()
interface{}
func (q *Deque) PopFront()
interface{}
func (q *Deque) Front() interface{}
C++ Go
#include <list> import "container/list”
func (l *List) PushBack(v
interface{}) *Element
func (l *List) PushFront(v
interface{}) *Element
std::list<int> l{1, 2, 3};
l.push_front(0);
l.push_back(4);
for(auto elem : l) {
std::cout << elem << 'n';
}
l := list.New()
e4 := l.PushBack(4)
e1 := l.PushFront(1)
for e := l.Front(); e != nil;
e = e.Next() {
fmt.Println(e.Value)
}
std::unordered_map<std::string, int>
map;
unorderedMap := make(map[string]int)
_, ok := unorderedMap["route"]
delete(unorderedMap, "route")
std::unordered_set<std::string> set; var m = make(map[string]struct{})
m["!"] = struct{}{}
_, ok := m["!"] // true
https://godbolt.org/z/xGAd12
https://groups.google.com/d/msg/golang-nuts/j_3n5wAZaXw/YkOdbCppAQAJ
https://groups.google.com/d/msg/golang-nuts/j_3n5wAZaXw/YkOdbCppAQAJ
Allocators?
● sync.Pool
● System allocator
● custom Slab old mechanism
● inability to put your allocator down -> not
custom: string, map, ...
Allоcator GO
● std:
○ allocator
○ polymorphic_allocator
● All custom
Allocator C++
Benchmarks!
C++ Go
#include <iostream>
#include <vector>
int main() {
int64_t sum = 0;
for (int e = 0; e < 200; e++) {
sum = 0;
std::vector<int64_t> x;
for (int i = 0; i < 1000000; i++) {
x.push_back(i);
}
std::vector<int64_t> y;
for (int i = 0; i < 1000000 - 1; i++) {
y.push_back(x[i] + x[i + 1]);
}
for (int i = 0; i < 1000000; i += 100) {
sum += y[i];
}
}
std::cout << sum << std::endl;
}
package main
import "fmt"
func main() {
var sum int64 = 0
for e := 0; e < 200; e++ {
sum = 0
var x []int64
for i := 0; i < 1000000; i++ {
x = append(x, int64(i))
}
var y []int64
for i := 0; i < 1000000-1; i++ {
y = append(y, x[i]+x[i+1])
}
for i := 0; i < 1000000; i += 100 {
sum += y[i]
}
}
fmt.Println(sum)
}
Go C++
go build bench-go.go  clang++ -m64 -o bench-cpp -O3 bench-
cpp.cpp 
✔ ~/go_vs_cpp
02:29 $ time ./bench-go
9999010000
real 0m1,785s
user 0m2,417s
sys 0m0,246s
✔ ~/go_vs_cpp
02:29 $ time ./bench-go
9999010000
real 0m1,809s
user 0m2,441s
sys 0m0,253s
✔ ~/go_vs_cpp
02:29 $ time ./bench-cpp
9999010000
real 0m0,868s
user 0m0,729s
sys 0m0,128s
✔ ~/go_vs_cpp
02:29 $ time ./bench-cpp
9999010000
real 0m0,875s
user 0m0,735s
sys 0m0,130s
Go C++
go build -gcflags=-B bench-go.go  clang++ -m64 -o bench-cpp -O3 bench-
cpp.cpp 
✔ ~/go_vs_cpp/I_vlxy_I 

01:37 $ time ./bench-go
1999802000000
real 0m0,350s
user 0m0,504s
sys 0m0,055s
✔ ~/go_vs_cpp/I_vlxy_I
01:37 $ time ./bench-go
1999802000000
real 0m0,352s
user 0m0,510s
sys 0m0,058s
✔ ~/go_vs_cpp/I_vlxy_I
01:37 $ time ./bench-cpp
1999802000000
real 0m0,511s
user 0m0,447s
sys 0m0,014s
✔ ~/go_vs_cpp/I_vlxy_I
01:39 $ time ./bench-cpp
1999802000000
real 0m0,488s
user 0m0,425s
sys 0m0,012s
C++* Go*
#include <iostream>
#include <vector>
int main() {
int64_t sum = 0;
std::vector<int64_t> x;
x.reserve(1000000);
std::vector<int64_t> y;
y.reserve(1000000);
for (int e = 0; e < 200; e++) {
x.clear();
y.clear();
for (int i = 0; i < 1000000; i++) {
x.push_back(i);
}
for (int i = 0; i < 1000000 - 1; i++) {
y.push_back(x[i] + x[i + 1]);
}
for (int i = 0; i < 1000000; i += 100) {
sum += y[i];
}
}
std::cout << sum << std::endl;
return 0;
}
package main
import "fmt"
func main() {
var sum int64 = 0
var x []int64
x = make([]int64,0,1000000)
var y []int64
y = make([]int64,0,1000000)
for e :=0; e<200; e++ {
x = x[:0]
y = y[:0]
for i :=0; i < 1000000; i++ {
x = append(x, int64(i))
}
for i :=0; i< 1000000-1; i++ {
y = append(y, x[i]+x[i+1])
}
for i:=0; i<1000000; i+=100 {
sum += y[i]
}
}
fmt.Println(sum)
}
C++* Go*
#include <iostream>
#include <vector>
int main() {
int64_t sum = 0;
std::vector<int64_t> x;
x.reserve(1000000);
std::vector<int64_t> y;
y.reserve(1000000);
for (int e = 0; e < 200; e++) {
x.clear();
y.clear();
for (int i = 0; i < 1000000; i++) {
x.push_back(i);
}
for (int i = 0; i < 1000000 - 1; i++) {
y.push_back(x[i] + x[i + 1]);
}
for (int i = 0; i < 1000000; i += 100) {
sum += y[i];
}
}
std::cout << sum << std::endl;
return 0;
}
package main
import "fmt"
func main() {
var sum int64 = 0
var x []int64
x = make([]int64,0,1000000)
var y []int64
y = make([]int64,0,1000000)
for e :=0; e<200; e++ {
x = x[:0]
y = y[:0]
for i :=0; i < 1000000; i++ {
x = append(x, int64(i))
}
for i :=0; i< 1000000-1; i++ {
y = append(y, x[i]+x[i+1])
}
for i:=0; i<1000000; i+=100 {
sum += y[i]
}
}
fmt.Println(sum)
}
C++** Go*
#include <iostream>
#include <array>
std::array<int64_t, 1000000> x;
std::array<int64_t, 1000000> y;
int main()
{
int64_t sum = 0;
for (int e = 0; e < 200; e++)
{
for (int i = 0; i < 1000000; i++)
{
x[i] = i;
}
for (int i = 0; i < 1000000 - 1; i++)
{
y[i] = x[i] + x[i + 1];
}
for (int i = 0; i < 1000000; i += 100)
{
sum += y[i];
}
}
std::cout << sum << std::endl;
return 0;
}
package main
import "fmt"
func main() {
var sum int64 = 0
var x []int64
x = make([]int64,0,1000000)
var y []int64
y = make([]int64,0,1000000)
for e :=0; e<200; e++ {
x = x[:0]
y = y[:0]
for i :=0; i < 1000000; i++ {
x = append(x, int64(i))
}
for i :=0; i< 1000000-1; i++ {
y = append(y, x[i]+x[i+1])
}
for i:=0; i<1000000; i+=100 {
sum += y[i]
}
}
fmt.Println(sum)
}
Go C++
go build -gcflags=-B bench-go.go  clang++ -m64 -o bench-cpp-array -
O3 bench-cpp-array.cpp 
✔ ~/go_vs_cpp/I_vlxy_I 

01:37 $ time ./bench-go
1999802000000
real 0m0,350s
user 0m0,504s
sys 0m0,055s
✔ ~/go_vs_cpp/I_vlxy_I
01:37 $ time ./bench-go
1999802000000
real 0m0,352s
user 0m0,510s
sys 0m0,058s
✔ ~/go_vs_cpp/I_vlxy_I
01:39 $ time ./bench-cpp-arrays
1999802000000
real 0m0,275s
user 0m0,256s
sys 0m0,009s
✔ ~/go_vs_cpp/I_vlxy_I
01:53 $ time ./bench-cpp-arrays
1999802000000
real 0m0,281s
user 0m0,255s
sys 0m0,012s
Cgo interface
•Very convenient way to generate Cgo
binding
•But they both use orthogonal run-time
environments
•And marshalling Go arguments to C stack is
slow as a hell
Cgo interface
https://www.cockroachlabs.com/blog/the-cost-and-complexity-of-cgo/
CockroachDB/cgobench
•Copying memory between Go and C comes
with a price
•But you could avoid it with dirty tricks
Cgo interface
•Copying memory between Go and C comes
with a price
•But you could avoid it with dirty tricks
Cgo interface
•Copying memory between Go and C comes
with a price
•But you could avoid it with dirty tricks
Cgo interface
•GPU
•The same as on previous slides…
Cgo interface
“Go is safe” they said
“Go is safe”
Ross Cox

“Go is defined to be a safe language. Indices into
array or string references must be in bounds; there
is no way to reinterpret the bits of one type as
another, no way to conjure a pointer out of thin air;
and there is no way to release memory, so no
chance of “dangling pointer” errors and the
associated memory corruption and instability.”
Russ Cox,"Off to the Races"
https://goplay.space/#ubOeLHZIgQD
Concurrency in GO
Concurrency in GO
•Primitives:
• Mutex/RWMutex
• Channel
• Atomic
•Sync.Map -> performance
•size(Goroutins) -> ?
•goroutins + threadpool
•smart wait: io, …
•memory barrier
Concurrency in C++
● Primitives:
○ thread
○ *Mutex
○ Atomic
○ ....
● Boost::context
● Boost::*
● C++ 20 coroutines
● memory barrier
Concurrency in Go
•They said Go channels will be easy
•They said it will be less error-prone
•But…
Concurrency bugs
https://blog.acolyer.org/2019/05/17/understanding-real-world-concurrency-bugs-in-go/
•And marshalling Go arguments to C stack is
slow as a hell
•goroutines not transferred between processes
•Api: Posix, windows, …
•Low-cost ipc :
• fork
• ....
Multiprocessing & NUMA in Go
•Api: Posix, windows, …
•Low-cost ipc :
• fork, ....
• Boost.Interprocess
• Boost.process
• Boost.*
Multiprocessing & NUMA in С++
Code Quality
• Only short and simple functions are inlined – less than 40
expressions. No function calls, loops, closures…
• Multiple cases when escape analysis gives up, e.g. any kind of
indirection (*p = …)
• Function calls, package boundaries, slice literals, subslicing and
indexing – all inhibits escape analysis
• Range assignment converted to memchr
Go optimizer limitations
https://github.com/golang/go/wiki/CompilerOptimizations
What about GCCGO?
• Which uses fully-featured GCC backend…
• And could proceed proper optimizations even
LTO…
• Looks like it’s out of sync with main Go
compiler
And nobody* uses it…
What about gccgo?
What about package-manager?
•Govendor was a pain. Looks irrelevant at the
moment
•But even then it was much better than lack
of wide-spread C++ PM.
•Vcpkg or Conan will help eventually here
•All eyes on WG21/SG15 (tooling)
Past experience with PM
Go package managers usage
https://www.jetbrains.com/lp/devecosystem-2019/go/
Package Managers in C++?
https://www.jetbrains.com/lp/devecosystem-2019/cpp/
Build systems in C++?
The History and Trends
ISOC++
Go
1.0
2009 2010 2011 2012 2013 2014 2015 2015 2017 2018
1.1 1.2 1.10
May 2013 Version 1.1 unicode code points in strings literals. 32 and 64 bit int, uint. 64-bit heap of tens of gigabytes.
December 2013 Version 1.2 10K threads. 4K > 8K stacks
June 2014 Version 1.3 no language changes
December 2014 Version 1.4 Much of runtime is in Go.
August 2015 Version 1.5 Self-hosted (in Go and assembler, without C). GC < 10millisecs.
February 2016 Version 1.6 no language changes
August 2016 Version 1.7 sse for x64. SSA-based x64 code generation.
February 2017 Version 1.8 More sse/avx instructions. GC 10..100 microsecs. Overhead deferred improved.. Overhead from Go to C improved
August 2017 Version 1.9 Type aliases in Go. Compilation of functions in parallel
February 2018 Version 1.10 359 x64 instructions supported.
August 2018 Version 1.11 no language changes.WASM. Preliminary support for modules.AVX512 in assembler.
February 2019 Version 1.12 no language changes.TLS 1.3. Improved modules.
Go
1.0
2009 2010 2011 2012 2013 2014 2015 2015 2017 2018
1.1 1.2 1.10
May 2013 Version 1.1 unicode code points in strings literals. 32 and 64 bit int, uint. 64-bit heap of tens of gigabytes.
December 2013 Version 1.2 10K threads. 4K > 8K stacks
August 2016 Version 1.7 sse for x64. SSA-based x64 code generation.
August 2017 Version 1.9 Type aliases in Go. Compilation of functions in parallel
GoSurvey2018
https://blog.golang.org/survey2018-results
How about management?
•Barrier to entry: 0-4 hours
•Time to expert: ≈3 month
Go team scalability
•Barrier to entry: 0-4 hours
•Time to expert: ≈3 month
•Excellent documentation
•Godoc for 3-party packages
Go team scalability
•Barrier to entry: 0-4 hours
•Time to expert: ≈3 month
•Excellent documentation
•Godoc for 3-party packages
•Unified codestyle
Go team scalability
•No unmaintainable makefiles
Cross-platform development in Go
// +build freebsd openbsd netbsd dragonfly
package fsnotify
import "golang.org/x/sys/unix”

const openMode = unix.O_NONBLOCK | unix.O_RDONLY
BSD kqueue
Cross-platform
// +build windows
package fsnotify
Windows watchers
•Own profiler (with web interface!)
•go test -bench
•Cross-platform asm
•Optimizing culture
Go simpler performance tuning
Salaries @ MoiKrug
https://habr.com/ru/company/moikrug/blog/461855/
https://habr.com/ru/company/moikrug/blog/461855/
https://habr.com/ru/company/moikrug/blog/461855/
https://habr.com/ru/company/moikrug/blog/464655/
Salary changes dynamics 2017-2019
https://habr.com/ru/company/moikrug/blog/464655/
Salary changes dynamics 2017-2019
https://habr.com/ru/company/moikrug/blog/464655/
Salary changes dynamics 2017-2019
https://habr.com/ru/company/moikrug/blog/464655/
Usage frequency changes dynamics 2017-2019
https://habr.com/ru/company/moikrug/blog/464655/
Usage frequency changes dynamics 2017-2019
Your vote?

More Related Content

What's hot

C++ TUTORIAL 9
C++ TUTORIAL 9C++ TUTORIAL 9
C++ TUTORIAL 9
Farhan Ab Rahman
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
Eleanor McHugh
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
Svet Ivantchev
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
Eleanor McHugh
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
Eleanor McHugh
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
Farhan Ab Rahman
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacionJeff Tu Pechito
 
C++ TUTORIAL 10
C++ TUTORIAL 10C++ TUTORIAL 10
C++ TUTORIAL 10
Farhan Ab Rahman
 
SPL 6.1 | Advanced problems on Operators and Math.h function in C
SPL 6.1 | Advanced problems on Operators and Math.h function in CSPL 6.1 | Advanced problems on Operators and Math.h function in C
SPL 6.1 | Advanced problems on Operators and Math.h function in C
Mohammad Imam Hossain
 
C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
Farhan Ab Rahman
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
Maxim Kulsha
 
Cn os-lp lab manual k.roshan
Cn os-lp lab manual k.roshanCn os-lp lab manual k.roshan
Cn os-lp lab manual k.roshanriturajj
 
C++ TUTORIAL 1
C++ TUTORIAL 1C++ TUTORIAL 1
C++ TUTORIAL 1
Farhan Ab Rahman
 
Frsa
FrsaFrsa
Frsa
_111
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
Adam Dudczak
 
Os lab file c programs
Os lab file c programsOs lab file c programs
Os lab file c programs
Kandarp Tiwari
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
Han Lee
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
Richard Fox
 
関数プログラミングことはじめ revival
関数プログラミングことはじめ revival関数プログラミングことはじめ revival
関数プログラミングことはじめ revival
Naoki Kitora
 

What's hot (20)

C++ TUTORIAL 9
C++ TUTORIAL 9C++ TUTORIAL 9
C++ TUTORIAL 9
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Go: It's Not Just For Google
Go: It's Not Just For GoogleGo: It's Not Just For Google
Go: It's Not Just For Google
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
C++ TUTORIAL 3
C++ TUTORIAL 3C++ TUTORIAL 3
C++ TUTORIAL 3
 
Ejercicios de programacion
Ejercicios de programacionEjercicios de programacion
Ejercicios de programacion
 
C++ TUTORIAL 10
C++ TUTORIAL 10C++ TUTORIAL 10
C++ TUTORIAL 10
 
SPL 6.1 | Advanced problems on Operators and Math.h function in C
SPL 6.1 | Advanced problems on Operators and Math.h function in CSPL 6.1 | Advanced problems on Operators and Math.h function in C
SPL 6.1 | Advanced problems on Operators and Math.h function in C
 
C++ TUTORIAL 4
C++ TUTORIAL 4C++ TUTORIAL 4
C++ TUTORIAL 4
 
Python легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачиPython легко и просто. Красиво решаем повседневные задачи
Python легко и просто. Красиво решаем повседневные задачи
 
Cn os-lp lab manual k.roshan
Cn os-lp lab manual k.roshanCn os-lp lab manual k.roshan
Cn os-lp lab manual k.roshan
 
C++ TUTORIAL 1
C++ TUTORIAL 1C++ TUTORIAL 1
C++ TUTORIAL 1
 
Frsa
FrsaFrsa
Frsa
 
Are we ready to Go?
Are we ready to Go?Are we ready to Go?
Are we ready to Go?
 
Os lab file c programs
Os lab file c programsOs lab file c programs
Os lab file c programs
 
String
StringString
String
 
Imugi: Compiler made with Python
Imugi: Compiler made with PythonImugi: Compiler made with Python
Imugi: Compiler made with Python
 
Generics and Inference
Generics and InferenceGenerics and Inference
Generics and Inference
 
関数プログラミングことはじめ revival
関数プログラミングことはじめ revival関数プログラミングことはじめ revival
関数プログラミングことはじめ revival
 

Similar to Go vs C++ - CppRussia 2019 Piter BoF

C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Cpp programs
Cpp programsCpp programs
Cpp programs
harman kaur
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Lab Question
Lab QuestionLab Question
The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212
Mahmoud Samir Fayed
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
Oliver N
 
I wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdfI wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdf
rishteygallery
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
premrings
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
The Software House
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
Neeru Mittal
 
The Ring programming language version 1.5.4 book - Part 25 of 185
The Ring programming language version 1.5.4 book - Part 25 of 185The Ring programming language version 1.5.4 book - Part 25 of 185
The Ring programming language version 1.5.4 book - Part 25 of 185
Mahmoud Samir Fayed
 
Pnno
PnnoPnno
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcional
tdc-globalcode
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
Roberto Pepato
 
Lập trình C
Lập trình CLập trình C
Lập trình C
Viet NguyenHoang
 
Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Er Ritu Aggarwal
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
Tor Ivry
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semesterDOSONKA Group
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperDeepak Singh
 

Similar to Go vs C++ - CppRussia 2019 Piter BoF (20)

C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Cpp programs
Cpp programsCpp programs
Cpp programs
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Lab Question
Lab QuestionLab Question
Lab Question
 
The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212The Ring programming language version 1.10 book - Part 33 of 212
The Ring programming language version 1.10 book - Part 33 of 212
 
Cpp c++ 1
Cpp c++ 1Cpp c++ 1
Cpp c++ 1
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 
I wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdfI wrote the following change it to having a header, main and cpp fi.pdf
I wrote the following change it to having a header, main and cpp fi.pdf
 
54602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee0108310154602399 c-examples-51-to-108-programe-ee01083101
54602399 c-examples-51-to-108-programe-ee01083101
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
The Ring programming language version 1.5.4 book - Part 25 of 185
The Ring programming language version 1.5.4 book - Part 25 of 185The Ring programming language version 1.5.4 book - Part 25 of 185
The Ring programming language version 1.5.4 book - Part 25 of 185
 
Pnno
PnnoPnno
Pnno
 
TDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação FuncionalTDC2016SP - Trilha Programação Funcional
TDC2016SP - Trilha Programação Funcional
 
Haskell 101
Haskell 101Haskell 101
Haskell 101
 
Lập trình C
Lập trình CLập trình C
Lập trình C
 
Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02Daapracticals 111105084852-phpapp02
Daapracticals 111105084852-phpapp02
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
Network lap pgms 7th semester
Network lap pgms 7th semesterNetwork lap pgms 7th semester
Network lap pgms 7th semester
 
Computer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paperComputer science-2010-cbse-question-paper
Computer science-2010-cbse-question-paper
 

More from Timur Safin

Инструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶ отладки в Tarantool
Инструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶  отладки в TarantoolИнструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶  отладки в Tarantool
Инструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶ отладки в Tarantool
Timur Safin
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоны
Timur Safin
 
Native json in the Cache' ObjectScript 2016.*
Native json in the Cache' ObjectScript 2016.*Native json in the Cache' ObjectScript 2016.*
Native json in the Cache' ObjectScript 2016.*
Timur Safin
 
InterSystems iKnow and Twitter API
InterSystems iKnow and Twitter APIInterSystems iKnow and Twitter API
InterSystems iKnow and Twitter API
Timur Safin
 
Multimodel Database Caché
Multimodel Database CachéMultimodel Database Caché
Multimodel Database Caché
Timur Safin
 
Implementation of community package manager
Implementation of community package managerImplementation of community package manager
Implementation of community package manager
Timur Safin
 
Новости Global summit 2015
Новости Global summit 2015Новости Global summit 2015
Новости Global summit 2015
Timur Safin
 
Approaching package manager
Approaching package managerApproaching package manager
Approaching package manager
Timur Safin
 

More from Timur Safin (8)

Инструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶ отладки в Tarantool
Инструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶  отладки в TarantoolИнструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶  отладки в Tarantool
Инструменты для з̶а̶х̶в̶а̶т̶а̶ ̶м̶и̶р̶а̶ отладки в Tarantool
 
Новый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоныНовый InterSystems: open-source, митапы, хакатоны
Новый InterSystems: open-source, митапы, хакатоны
 
Native json in the Cache' ObjectScript 2016.*
Native json in the Cache' ObjectScript 2016.*Native json in the Cache' ObjectScript 2016.*
Native json in the Cache' ObjectScript 2016.*
 
InterSystems iKnow and Twitter API
InterSystems iKnow and Twitter APIInterSystems iKnow and Twitter API
InterSystems iKnow and Twitter API
 
Multimodel Database Caché
Multimodel Database CachéMultimodel Database Caché
Multimodel Database Caché
 
Implementation of community package manager
Implementation of community package managerImplementation of community package manager
Implementation of community package manager
 
Новости Global summit 2015
Новости Global summit 2015Новости Global summit 2015
Новости Global summit 2015
 
Approaching package manager
Approaching package managerApproaching package manager
Approaching package manager
 

Recently uploaded

Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 

Recently uploaded (20)

Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 

Go vs C++ - CppRussia 2019 Piter BoF

  • 3.
  • 5. • There is no way to centralize error handling, and you doing it the “old good way” (check after each step): No exceptions defer ts.Close() conf := newConf(ts.URL) _, err := conf.Exchange(context.Background(), "exchange- code") if err == nil { t.Fatalf("got no error, expected one") } _, ok := err.(*RetrieveError) if !ok { t.Fatalf("got %T error, expected *RetrieveError; error was: %v", err, err)
  • 6. •So observations are that average Go function length might be up to 3x longer if to correctly handle all errors (than comparable C*/C++ code) No exceptions * C at least has a preprocessor
  • 7. •"If it walks like a duck and it quacks like a duck, then it must be a duck” •In duck typing, an object's suitability is determined by the presence of certain methods and properties, rather than the type of the object itself. Duck Typing vs True https://en.wikipedia.org/wiki/Duck_typing
  • 8. type Reader struct {     r io.ReaderAt     File []*File     Comment string     decompressors map[uint16]Decompressor }
 ...
 func (z *Reader) init(r io.ReaderAt, size int64) error {     end, err := readDirectoryEnd(r, size)     if err != nil {         return err     }     ... } ... func (z *Reader) RegisterDecompressor(method uint16, dcomp Decompressor) {     if z.decompressors == nil {         z.decompressors = make(map[uint16]Decompressor)     }     z.decompressors[method] = dcomp } UglyClasses
  • 9. type Reader struct {     r io.ReaderAt     File []*File     Comment string     decompressors map[uint16]Decompressor }
 ...
 func (z *Reader) init(r io.ReaderAt, size int64) error {     end, err := readDirectoryEnd(r, size)     if err != nil {         return err     }     ... } ... func (z *Reader) RegisterDecompressor(method uint16, dcomp Decompressor) {     if z.decompressors == nil {         z.decompressors = make(map[uint16]Decompressor)     }     z.decompressors[method] = dcomp } UglyClasses
  • 10. MODULE Lists; TYPE List* = POINTER TO ListNode; ListNode = RECORD value : Integer; next : List; END; PROCEDURE (l : List) Add* (v : Integer); BEGIN IF l = NIL THEN NEW(l); (* create record instance *) l.value := v ELSE l.next.Add(v) (* recursive call to .add(n) *) END END Add; Oberon-2 UglyClasses
  • 11. LL(1) grammar with C-like keywords var prohibitionaryDialArgTests = []struct { network string address string }{ {"tcp4", "127.0.0.1"}, {"tcp6", "::ffff:127.0.0.1"}, } func DoProhibitionaryDialArg(t *testing.T) (error) { Go const prohibitionaryDialArgTests : array [1..2] of record network : string; address : string; end = ( (network: ‘tcp4’, address: ‘127.0.0.1’), (network: ‘tcp6’, address: ‘::ffff: 127.0.0.1’) ); function DoProhibitionaryDialArg(var t: Testing.T) : TError;
 Pascal Pascal/Oberon syntax which mimics C
  • 12. •Order of keywords in declaration •No name overloads • No generics • No pointer arithmetic • Fast compiler • Weak optimizer • Source modules-based build • blahblahthousandsmoreweakanalogues More Pascal/Oberon like…
  • 14. C++ Go std::vector<int> vector; vector[i] vector := []int{} vector[i] std::stack<int> stack; stack := []int{} stack.push(value); stack = append(stack, value) value = stack.top(); stack.pop() stack, value = stack[:len(stack)-1], stack[len(stack)-1] std::deque<int> q{}; q.push_back(value); q.pop_front(); import "github.com/gammazero/deque” func (q *Deque) PushBack(elem interface{}) func (q *Deque) PopBack() interface{} func (q *Deque) PopFront() interface{} func (q *Deque) Front() interface{}
  • 15. C++ Go #include <list> import "container/list” func (l *List) PushBack(v interface{}) *Element func (l *List) PushFront(v interface{}) *Element std::list<int> l{1, 2, 3}; l.push_front(0); l.push_back(4); for(auto elem : l) { std::cout << elem << 'n'; } l := list.New() e4 := l.PushBack(4) e1 := l.PushFront(1) for e := l.Front(); e != nil; e = e.Next() { fmt.Println(e.Value) } std::unordered_map<std::string, int> map; unorderedMap := make(map[string]int) _, ok := unorderedMap["route"] delete(unorderedMap, "route") std::unordered_set<std::string> set; var m = make(map[string]struct{}) m["!"] = struct{}{} _, ok := m["!"] // true
  • 20. ● sync.Pool ● System allocator ● custom Slab old mechanism ● inability to put your allocator down -> not custom: string, map, ... Allоcator GO
  • 21. ● std: ○ allocator ○ polymorphic_allocator ● All custom Allocator C++
  • 23. C++ Go #include <iostream> #include <vector> int main() { int64_t sum = 0; for (int e = 0; e < 200; e++) { sum = 0; std::vector<int64_t> x; for (int i = 0; i < 1000000; i++) { x.push_back(i); } std::vector<int64_t> y; for (int i = 0; i < 1000000 - 1; i++) { y.push_back(x[i] + x[i + 1]); } for (int i = 0; i < 1000000; i += 100) { sum += y[i]; } } std::cout << sum << std::endl; } package main import "fmt" func main() { var sum int64 = 0 for e := 0; e < 200; e++ { sum = 0 var x []int64 for i := 0; i < 1000000; i++ { x = append(x, int64(i)) } var y []int64 for i := 0; i < 1000000-1; i++ { y = append(y, x[i]+x[i+1]) } for i := 0; i < 1000000; i += 100 { sum += y[i] } } fmt.Println(sum) }
  • 24. Go C++ go build bench-go.go  clang++ -m64 -o bench-cpp -O3 bench- cpp.cpp  ✔ ~/go_vs_cpp 02:29 $ time ./bench-go 9999010000 real 0m1,785s user 0m2,417s sys 0m0,246s ✔ ~/go_vs_cpp 02:29 $ time ./bench-go 9999010000 real 0m1,809s user 0m2,441s sys 0m0,253s ✔ ~/go_vs_cpp 02:29 $ time ./bench-cpp 9999010000 real 0m0,868s user 0m0,729s sys 0m0,128s ✔ ~/go_vs_cpp 02:29 $ time ./bench-cpp 9999010000 real 0m0,875s user 0m0,735s sys 0m0,130s
  • 25. Go C++ go build -gcflags=-B bench-go.go  clang++ -m64 -o bench-cpp -O3 bench- cpp.cpp  ✔ ~/go_vs_cpp/I_vlxy_I 
 01:37 $ time ./bench-go 1999802000000 real 0m0,350s user 0m0,504s sys 0m0,055s ✔ ~/go_vs_cpp/I_vlxy_I 01:37 $ time ./bench-go 1999802000000 real 0m0,352s user 0m0,510s sys 0m0,058s ✔ ~/go_vs_cpp/I_vlxy_I 01:37 $ time ./bench-cpp 1999802000000 real 0m0,511s user 0m0,447s sys 0m0,014s ✔ ~/go_vs_cpp/I_vlxy_I 01:39 $ time ./bench-cpp 1999802000000 real 0m0,488s user 0m0,425s sys 0m0,012s
  • 26. C++* Go* #include <iostream> #include <vector> int main() { int64_t sum = 0; std::vector<int64_t> x; x.reserve(1000000); std::vector<int64_t> y; y.reserve(1000000); for (int e = 0; e < 200; e++) { x.clear(); y.clear(); for (int i = 0; i < 1000000; i++) { x.push_back(i); } for (int i = 0; i < 1000000 - 1; i++) { y.push_back(x[i] + x[i + 1]); } for (int i = 0; i < 1000000; i += 100) { sum += y[i]; } } std::cout << sum << std::endl; return 0; } package main import "fmt" func main() { var sum int64 = 0 var x []int64 x = make([]int64,0,1000000) var y []int64 y = make([]int64,0,1000000) for e :=0; e<200; e++ { x = x[:0] y = y[:0] for i :=0; i < 1000000; i++ { x = append(x, int64(i)) } for i :=0; i< 1000000-1; i++ { y = append(y, x[i]+x[i+1]) } for i:=0; i<1000000; i+=100 { sum += y[i] } } fmt.Println(sum) }
  • 27. C++* Go* #include <iostream> #include <vector> int main() { int64_t sum = 0; std::vector<int64_t> x; x.reserve(1000000); std::vector<int64_t> y; y.reserve(1000000); for (int e = 0; e < 200; e++) { x.clear(); y.clear(); for (int i = 0; i < 1000000; i++) { x.push_back(i); } for (int i = 0; i < 1000000 - 1; i++) { y.push_back(x[i] + x[i + 1]); } for (int i = 0; i < 1000000; i += 100) { sum += y[i]; } } std::cout << sum << std::endl; return 0; } package main import "fmt" func main() { var sum int64 = 0 var x []int64 x = make([]int64,0,1000000) var y []int64 y = make([]int64,0,1000000) for e :=0; e<200; e++ { x = x[:0] y = y[:0] for i :=0; i < 1000000; i++ { x = append(x, int64(i)) } for i :=0; i< 1000000-1; i++ { y = append(y, x[i]+x[i+1]) } for i:=0; i<1000000; i+=100 { sum += y[i] } } fmt.Println(sum) }
  • 28. C++** Go* #include <iostream> #include <array> std::array<int64_t, 1000000> x; std::array<int64_t, 1000000> y; int main() { int64_t sum = 0; for (int e = 0; e < 200; e++) { for (int i = 0; i < 1000000; i++) { x[i] = i; } for (int i = 0; i < 1000000 - 1; i++) { y[i] = x[i] + x[i + 1]; } for (int i = 0; i < 1000000; i += 100) { sum += y[i]; } } std::cout << sum << std::endl; return 0; } package main import "fmt" func main() { var sum int64 = 0 var x []int64 x = make([]int64,0,1000000) var y []int64 y = make([]int64,0,1000000) for e :=0; e<200; e++ { x = x[:0] y = y[:0] for i :=0; i < 1000000; i++ { x = append(x, int64(i)) } for i :=0; i< 1000000-1; i++ { y = append(y, x[i]+x[i+1]) } for i:=0; i<1000000; i+=100 { sum += y[i] } } fmt.Println(sum) }
  • 29. Go C++ go build -gcflags=-B bench-go.go  clang++ -m64 -o bench-cpp-array - O3 bench-cpp-array.cpp  ✔ ~/go_vs_cpp/I_vlxy_I 
 01:37 $ time ./bench-go 1999802000000 real 0m0,350s user 0m0,504s sys 0m0,055s ✔ ~/go_vs_cpp/I_vlxy_I 01:37 $ time ./bench-go 1999802000000 real 0m0,352s user 0m0,510s sys 0m0,058s ✔ ~/go_vs_cpp/I_vlxy_I 01:39 $ time ./bench-cpp-arrays 1999802000000 real 0m0,275s user 0m0,256s sys 0m0,009s ✔ ~/go_vs_cpp/I_vlxy_I 01:53 $ time ./bench-cpp-arrays 1999802000000 real 0m0,281s user 0m0,255s sys 0m0,012s
  • 31. •Very convenient way to generate Cgo binding •But they both use orthogonal run-time environments •And marshalling Go arguments to C stack is slow as a hell Cgo interface
  • 33. •Copying memory between Go and C comes with a price •But you could avoid it with dirty tricks Cgo interface
  • 34. •Copying memory between Go and C comes with a price •But you could avoid it with dirty tricks Cgo interface
  • 35. •Copying memory between Go and C comes with a price •But you could avoid it with dirty tricks Cgo interface
  • 36.
  • 37. •GPU •The same as on previous slides… Cgo interface
  • 38. “Go is safe” they said
  • 39. “Go is safe” Ross Cox
 “Go is defined to be a safe language. Indices into array or string references must be in bounds; there is no way to reinterpret the bits of one type as another, no way to conjure a pointer out of thin air; and there is no way to release memory, so no chance of “dangling pointer” errors and the associated memory corruption and instability.” Russ Cox,"Off to the Races"
  • 42. Concurrency in GO •Primitives: • Mutex/RWMutex • Channel • Atomic •Sync.Map -> performance •size(Goroutins) -> ? •goroutins + threadpool •smart wait: io, … •memory barrier
  • 43. Concurrency in C++ ● Primitives: ○ thread ○ *Mutex ○ Atomic ○ .... ● Boost::context ● Boost::* ● C++ 20 coroutines ● memory barrier
  • 44. Concurrency in Go •They said Go channels will be easy •They said it will be less error-prone •But…
  • 46. •And marshalling Go arguments to C stack is slow as a hell •goroutines not transferred between processes •Api: Posix, windows, … •Low-cost ipc : • fork • .... Multiprocessing & NUMA in Go
  • 47. •Api: Posix, windows, … •Low-cost ipc : • fork, .... • Boost.Interprocess • Boost.process • Boost.* Multiprocessing & NUMA in С++
  • 49. • Only short and simple functions are inlined – less than 40 expressions. No function calls, loops, closures… • Multiple cases when escape analysis gives up, e.g. any kind of indirection (*p = …) • Function calls, package boundaries, slice literals, subslicing and indexing – all inhibits escape analysis • Range assignment converted to memchr Go optimizer limitations https://github.com/golang/go/wiki/CompilerOptimizations
  • 51. • Which uses fully-featured GCC backend… • And could proceed proper optimizations even LTO… • Looks like it’s out of sync with main Go compiler And nobody* uses it… What about gccgo?
  • 53. •Govendor was a pain. Looks irrelevant at the moment •But even then it was much better than lack of wide-spread C++ PM. •Vcpkg or Conan will help eventually here •All eyes on WG21/SG15 (tooling) Past experience with PM
  • 54. Go package managers usage https://www.jetbrains.com/lp/devecosystem-2019/go/
  • 55. Package Managers in C++? https://www.jetbrains.com/lp/devecosystem-2019/cpp/
  • 57. The History and Trends
  • 59. Go 1.0 2009 2010 2011 2012 2013 2014 2015 2015 2017 2018 1.1 1.2 1.10 May 2013 Version 1.1 unicode code points in strings literals. 32 and 64 bit int, uint. 64-bit heap of tens of gigabytes. December 2013 Version 1.2 10K threads. 4K > 8K stacks June 2014 Version 1.3 no language changes December 2014 Version 1.4 Much of runtime is in Go. August 2015 Version 1.5 Self-hosted (in Go and assembler, without C). GC < 10millisecs. February 2016 Version 1.6 no language changes August 2016 Version 1.7 sse for x64. SSA-based x64 code generation. February 2017 Version 1.8 More sse/avx instructions. GC 10..100 microsecs. Overhead deferred improved.. Overhead from Go to C improved August 2017 Version 1.9 Type aliases in Go. Compilation of functions in parallel February 2018 Version 1.10 359 x64 instructions supported. August 2018 Version 1.11 no language changes.WASM. Preliminary support for modules.AVX512 in assembler. February 2019 Version 1.12 no language changes.TLS 1.3. Improved modules.
  • 60. Go 1.0 2009 2010 2011 2012 2013 2014 2015 2015 2017 2018 1.1 1.2 1.10 May 2013 Version 1.1 unicode code points in strings literals. 32 and 64 bit int, uint. 64-bit heap of tens of gigabytes. December 2013 Version 1.2 10K threads. 4K > 8K stacks August 2016 Version 1.7 sse for x64. SSA-based x64 code generation. August 2017 Version 1.9 Type aliases in Go. Compilation of functions in parallel
  • 63. •Barrier to entry: 0-4 hours •Time to expert: ≈3 month Go team scalability
  • 64. •Barrier to entry: 0-4 hours •Time to expert: ≈3 month •Excellent documentation •Godoc for 3-party packages Go team scalability
  • 65. •Barrier to entry: 0-4 hours •Time to expert: ≈3 month •Excellent documentation •Godoc for 3-party packages •Unified codestyle Go team scalability
  • 67. // +build freebsd openbsd netbsd dragonfly package fsnotify import "golang.org/x/sys/unix”
 const openMode = unix.O_NONBLOCK | unix.O_RDONLY BSD kqueue Cross-platform // +build windows package fsnotify Windows watchers
  • 68. •Own profiler (with web interface!) •go test -bench •Cross-platform asm •Optimizing culture Go simpler performance tuning