Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Optimized version of leftpad in plain C

Name: Anonymous 2016-03-23 21:32

#include <string.h>

static const char*
string_add(const char* first, const char* second)
{
const char* result = malloc(strlen(first) + strlen(second) + 1);
strcat(result, first);
strcat(result, second);
return result;
}

const char*
leftpad(const char* str, size_t len, char ch)
{
int i = -1;

if (ch == 0) ch = ' ';

int len = strlen(str);

while (++i < len) {
char buf[2] = { 0 };
buf[0] = ch;
str = string_add(buf, str);
}

return str;
}

Name: Anonymous 2016-04-12 0:27

//prog.go
package prog

func LeftPad(s string, l int, pad byte) string {
diff := l - len(s)
if diff <= 0 {
return s
}

b := make([]byte, l)
for i := 0; i < diff; i++ {
b[i] = pad
}
copy(b[diff:], s)
return string(b)
}

//prog_test.go
package prog

import "testing"

func BenchmarkLeftPadHMA(b *testing.B) {
for n := 0; n < b.N; n++ {
LeftPad("hax my anus", 20, ' ')
}
}


$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkLeftPadHMA-8 10000000 124 ns/op
ok _/C_/Users/progrider/code/go/prog 1.419s


Unbeatable

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List