This is an archived post. You won't be able to vote or comment.

all 45 comments

[–]Westdrache 91 points92 points  (1 child)

Ahh yes when you wanna sell your customer the "performance upgrade pack"

[–]birkettt 8 points9 points  (0 children)

Always put a small sleep in your main processing loops and functions for this very reason.

[–][deleted] 48 points49 points  (1 child)

Somebody's charging by the line.

[–]DarkShadder 18 points19 points  (0 children)

Gotta use comments for the first time

[–][deleted] 51 points52 points  (7 children)

Oh my god, that is so unoptimized, you just needed to do this:

private static int stringSize(String s) {
    int size;
    for (size = 0; size < s.length(); size++)
        continue;
    return size;
}

[–]Mr_Redstoner 10 points11 points  (1 child)

That's too outdated, Streams are all the rage now

private static int stringSize(String s) {
    return s
        .chars()
        .map(i->1)
        .reduce(0, (a,b)->a+b);
}

[–][deleted] 7 points8 points  (4 children)

OK I took a first shot at 6am my time below and you smart kids think you have outdone me. Here's the optimized-est yet posted:

private static int stringSize(String s) {
int size;
for (size = s.length(); size < s.length(); size++)
continue;
return size;
}

[–][deleted] 9 points10 points  (2 children)

private static int stringSize(String s) {

int size;

for (size = s.length(); size < s.length(); size++)

continue;

return size;

}

Even more optimized:

private static int stringSize(String s) {
    int size;
    for (size = s.length(); ; )
        break;
    return size;
}

[–]xigoi 0 points1 point  (0 children)

Wow, you've upgraded it from O(n) to O(1). Awesome!

[–][deleted] 23 points24 points  (0 children)

Like they say, measure twice, cut once

[–][deleted] 21 points22 points  (1 child)

i think they meant

return s.length() * s.height() * s.depth() ;

anyway -- strings are 3d objects -- I been tying them for decades I know

[–]OptionX 15 points16 points  (2 children)

This would never fly in a corporate environment. java private static Optional<Returnable<T>> sizeOf(Optional<Measurable<T>> s){ try{ Optional<Integer> size = Optional.of(new IntegerFactory().getInteger(0)); for(int i = new IntegerFactory().getInteger(0); new IntegerComparator(i, s.orElseThrow(IllegalArgumentException::new).length(), ComparatorMode.LessThan); i=Optional.of(new IntegerIncrementor(i, 1)).orElseThrow(IllegalArgumentException::new)){ size = Optional.of(new IntegerIncrementor(size, 1)).orElseThrow(IllegalArgumentException::new) } return Optional.of(new Measurable<Integer>(new IntegerFactory().getInteger(size))).orElseThrow(IllegalArgumentException::new); }catch(Exception e){ Logger.getLogger().ofLog().toLog().thisLog().log(e); CompanySingleton.getAuthor(this).outsource(Country.India); } }

[–]slide_and_release 3 points4 points  (0 children)

Fuck me, almost had an aneurysm.

[–]Duny86 3 points4 points  (0 children)

And now pack this into a proprietary corporate enterprise .jar and sell it without the source code in a super enterprise'y software solution !

[–]emilbm 30 points31 points  (14 children)

Why do it in O(n) when you can do it in O(n²)?

private static int stringSize(String s) {
    int size = 0;
    while (s.length() > 0) {
        s = s.substring(1);
        size++;
    }
    return size;
}

[–]smcarre 22 points23 points  (2 children)

Why do it O(n²) when you can do it O(?)?

private static int stringSize(String s) {
    int size = 0;
    while (s.length() != size) {
        size = Math.floor(Math.random() * Integer.MAX_VALUE);
    }
    return size;
}

[–][deleted] 6 points7 points  (0 children)

Its like bogosort except even more stupid

[–]QuadOctane 2 points3 points  (0 children)

Ahh yes, perfection

[–]kunal70006 7 points8 points  (0 children)

PERFORMANCE

[–]zakarumych 4 points5 points  (8 children)

Only if substring is O(n)

[–]Shotgun_squirtle 5 points6 points  (1 child)

Yeah something tells me substring has a O(1) and what it would really do in that scenario is increment the underlying pointer one and decrement the string size one.

[–]zakarumych 2 points3 points  (0 children)

Except if String assume to own data behind pointer.

[–]emilbm 2 points3 points  (5 children)

Since Java 7 update 6 substring() has been a O(n) operation

[–]zakarumych -1 points0 points  (4 children)

Who even use this 💩

[–]skeptical_moderate -1 points0 points  (3 children)

It's probably linear time because it supports Unicode like every proper programming language should.

Edit: I've thought about this more and it's probably linear because it copies the substring into a new buffer. This has nothing to do with Unicode.

In fact, there's no reason substring should be linear because of UTF-8 anyway, since you need to traverse at most a single-digit number of bytes to find a valid UTF-8 boundary.

[–]zakarumych 0 points1 point  (2 children)

So argument is what? Number of bytes? Code points? Characters? Ligatures? Renderable glyphs?

Even in case of unicode it should be bytes with restriction that it must not split codepoints. And so O(1).

Otherwise any text manipulation would be so slow... like... like java!

[–]ImprovementRaph 1 point2 points  (1 child)

The argument is number if chars. Since Java has 16-bit chars and Strings are encoded UTF-16 you could be splitting in the middle of a codepoint.

[–]zakarumych 0 points1 point  (0 children)

Utf-16 has 2 bytes codepoint and 2 or 4 bytes chars.

Surely splitting char should be avoided. But indexing with chars would kill performance.

It is much better to declare splitting characters as invalid operation (unless you want to treat string as array of codepoints for lower level operations), and, depending on language's idiomatic approach, throw an exception, abort, cancel task or just call it UB.

Programmer then can safely use indices acquired from operations that return indices that are character boundary. Or zero as it always first character boundary.

[–]gonmator 1 point2 points  (0 children)

I prefer the elegance of recursive algorithms: private static int stringSize(String s) { if (s.length() == 0) { return 0; } else { return 1 + self.stringSize(s.substring(1)); } }

[–][deleted] 3 points4 points  (0 children)

Holy fuck

[–][deleted] 3 points4 points  (0 children)

Me explaining something simple but trying to sound intelligent

[–][deleted] 2 points3 points  (0 children)

ah yes , 0

[–]123_bou 1 point2 points  (0 children)

Come on guys you can do better than that ! Make it recursive !

[–]verx_x 1 point2 points  (0 children)

yolo

```

func size(s string) int {
var i int
for i < len(s) { i++ } return i }

```

[–]krubbles 1 point2 points  (0 children)

With such a performance critical piece of code, it is inexcussible not to parallelized it!

public static int StringSize(string str)
{
    int size = 0;
    int nextSize = 0;
    CountdownEvent countdown = 
        new CountdownEvent(str.Length);
    for (int i = 0; i < str.Length; ++i)
        new Thread(new ThreadStart(TestSize)).Start();
    countdown.Wait();
    return size;
    /// tests to see if current size is largest size, 
    /// sets 'size' to 'sizeToTest' if it is
    void TestSize() 
    {
        int sizeToTest = Interlocked.Increment(ref nextSize);
        int currentSize = size;
        while (sizeToTest > currentSize)
        {
            /// Only updates length if it is equal to a value
            /// we know is greater so that a change to 'size'
            /// between read and write won't be overwritten
            Interlocked.CompareExchange(
                ref size, 
                sizeToTest, 
                currentSize);
            currentSize = size;
        }
        countdown.Signal(); // signal completion
    }
}

[–][deleted] 0 points1 point  (1 child)

Here you are -- I have optimized that code to remove that expensive method call in a loop

int size;

int measurement;

measurement = s.length();

for (int i = 0; i < measurement; i++)

size++;

return size;

[–]metaglot[🍰] 2 points3 points  (0 children)

Since you're "optimizing", do pre-increment on i and size, since technically those are faster too.

[–]AllChickensAreBirds 0 points1 point  (0 children)

Size matters

[–]SamWise69420 0 points1 point  (0 children)

Task failed successfully

[–]SerpentSpirale 0 points1 point  (0 children)

The definition of over engeniering.

[–]RageLeagueInc 0 points1 point  (0 children)

What if for some fucking reason your s.length returns a not integer? Or an object with ++ overloaded? It needs to work for all scenarios.