Skip to content

Conversation

@codeflash-ai
Copy link
Contributor

@codeflash-ai codeflash-ai bot commented Jan 16, 2026

📄 13% (0.13x) speedup for toTitleCase in code_to_optimize_js/string_utils.js

⏱️ Runtime : 468 microseconds 412 microseconds (best of 250 runs)

📝 Explanation and details

The optimized code achieves a 13% speedup by eliminating multiple intermediate array allocations and reducing function call overhead.

Key optimizations:

  1. Single-pass character iteration: Instead of split()map()join() which creates multiple intermediate arrays, the optimized version processes each character once in a loop, building the result string directly.

  2. Eliminates array overhead: The original approach:

    The optimized version only allocates the final result string.

  3. Reduces function calls: Eliminates array method overhead (split, map, join) and per-word string methods (charAt, slice). Instead uses simple character-by-character conditionals.

  4. State-based capitalization: The capitalizeNext flag efficiently tracks when to capitalize without needing to identify word boundaries upfront.

Performance characteristics by test type:

  • Best gains: Tests with many short words (e.g., "a b c", "hello world", 500-word documents) benefit most, as they maximize the impact of avoiding per-word string allocations
  • Moderate gains: Mixed-case normalization and large single words still benefit from reduced overhead
  • Edge cases: Empty strings, whitespace-only inputs now have early returns and simpler logic

The optimization is particularly effective for typical use cases involving multiple words, which aligns with the common usage patterns shown in the test suite where most tests involve 2-500 words separated by spaces.

Correctness verification report:

Test Status
⚙️ Existing Unit Tests 🔘 None Found
🌀 Generated Regression Tests 54 Passed
⏪ Replay Tests 🔘 None Found
🔎 Concolic Coverage Tests 🔘 None Found
📊 Tests Coverage 100.0%
🌀 Click to see Generated Regression Tests
// imports
const { toTitleCase } = require('../string_utils');

// unit tests
describe('toTitleCase', () => {
    // Basic Test Cases
    describe('Basic functionality', () => {
        test('should handle normal input', () => {
            // Normal two-word lowercase input
            expect(toTitleCase('hello world')).toBe('Hello World');
        });

        test('should capitalize a single word', () => {
            // Single word should have only its first character uppercased
            expect(toTitleCase('javascript')).toBe('Javascript');
        });

        test('should normalize mixed case words', () => {
            // Mixed case input should be lowercased then each word capitalized
            expect(toTitleCase('mIxEd CaSe')).toBe('Mixed Case');
        });

        test('should leave an already title-cased string effectively unchanged', () => {
            // Already title-cased input remains the same after function logic
            expect(toTitleCase('Hello World')).toBe('Hello World');
        });
    });

    // Edge Test Cases
    describe('Edge cases', () => {
        test('should return empty string when given empty string', () => {
            // Empty string should remain empty
            expect(toTitleCase('')).toBe('');
        });

        test('should preserve only-spaces input (maintain spacing)', () => {
            // Multiple spaces should be preserved exactly (split/join on ' ' keeps spacing)
            expect(toTitleCase('   ')).toBe('   ');
        });

        test('should preserve multiple spaces between words', () => {
            // Double spaces between words are preserved and capitalization applied to word characters
            expect(toTitleCase('hello  world')).toBe('Hello  World');
        });

        test('should preserve leading and trailing spaces while capitalizing words', () => {
            // Leading/trailing spaces are preserved by split/join on ' '
            expect(toTitleCase('  hello world  ')).toBe('  Hello World  ');
        });

        test('should handle tabs and newlines as ordinary characters (no split on them)', () => {
            // Since splitting is only on ASCII space, tabs/newlines stay inside words.
            // Only the very first character of the whole string will be capitalized in this case.
            const input = 'hello\tworld\nnew';
            expect(toTitleCase(input)).toBe('Hello\tworld\nnew');
        });

        test('should handle punctuation inside words (hyphen, apostrophe) without splitting', () => {
            // Hyphenated and apostrophes are kept as part of the word; only first char is capitalized
            expect(toTitleCase("hello-world")).toBe("Hello-world");
            expect(toTitleCase("o'clock")).toBe("O'clock");
            expect(toTitleCase("mother-in-law")).toBe("Mother-in-law");
        });

        test('should handle numbers and mixed alphanumerics', () => {
            // Numbers remain untouched; alphabetic part is lowercased then capitalized
            expect(toTitleCase('123 abc')).toBe('123 Abc');
            expect(toTitleCase('version2 update')).toBe('Version2 Update');
        });

        test('should handle unicode and accented characters correctly', () => {
            // Accented characters should be lowercased then first character uppercased (Unicode-aware)
            expect(toTitleCase('ÉLAN VITAL')).toBe('Élan Vital');
        });

        test('should handle emoji as first character of a word', () => {
            // Emoji should be preserved; alphabetic words after emoji get capitalized independently
            expect(toTitleCase('😊 smile')).toBe('😊 Smile');
            // If emoji is the only "word", it should remain the same
            expect(toTitleCase('😊')).toBe('😊');
        });

        test('should throw when non-string (null/undefined/number/object) is provided', () => {
            // toTitleCase calls String.prototype.toLowerCase; non-strings should cause an error
            expect(() => toTitleCase(null)).toThrow();
            expect(() => toTitleCase(undefined)).toThrow();
            expect(() => toTitleCase(123)).toThrow();
            expect(() => toTitleCase({})).toThrow();
            expect(() => toTitleCase([])).toThrow();
        });
    });

    // Large Scale Test Cases
    describe('Performance tests', () => {
        test('should handle large inputs efficiently and correctly (500 words)', () => {
            // Construct a large input with 500 simple words (under 1000 elements as required).
            const count = 500;
            const words = Array.from({ length: count }, (_, i) => `word${i}`);
            const input = words.join(' ');
            const output = toTitleCase(input);

            // Split result and assert the number of words is preserved
            const outWords = output.split(' ');
            expect(outWords).toHaveLength(count);

            // Assert first, middle, and last words are capitalized as expected
            expect(outWords[0]).toBe('Word0');
            expect(outWords[Math.floor(count / 2)]).toBe(`Word${Math.floor(count / 2)}`);
            expect(outWords[count - 1]).toBe(`Word${count - 1}`);
        });

        test('should handle another sizable input with varied tokens (250 words including punctuation)', () => {
            // Build a 250-word string mixing alpha, numeric, and punctuation tokens.
            const pieces = Array.from({ length: 250 }, (_, i) => {
                if (i % 5 === 0) return `item-${i}`; // hyphenated
                if (i % 5 === 1) return `O'${i}`; // apostrophe-like
                if (i % 5 === 2) return `NUM${i}`; // uppercase block
                if (i % 5 === 3) return `${i}_value`; // underscore
                return `emoji${i} 😊`; // includes emoji as separate token
            });

            const input = pieces.join(' ');
            const output = toTitleCase(input);

            // Basic correctness checks without iterating an excessive number of times
            const outWords = output.split(' ');
            expect(outWords).toHaveLength(pieces.length * 2 - pieces.filter(p => p.includes(' ')).length || pieces.length);

            // Spot check a few positions to ensure capitalization rules apply
            expect(output.startsWith('Item-0') || output.startsWith("Item-0")).toBe(true); // first token hyphenated -> 'Item-0'
            expect(output).toContain("O'1".replace("O'1", "O'1")); // ensures apostrophe token still present (capitalization applied)
            expect(output).toContain('Num2'); // NUM2 -> num2 -> Num2
        });
    });
});
// imports
const { toTitleCase } = require('../string_utils');

// unit tests
describe('toTitleCase', () => {
    // Basic Test Cases
    describe('Basic functionality', () => {
        test('should handle normal input with single word', () => {
            expect(toTitleCase('hello')).toBe('Hello');
        });

        test('should handle normal input with multiple words', () => {
            expect(toTitleCase('hello world')).toBe('Hello World');
        });

        test('should handle input with mixed case', () => {
            expect(toTitleCase('HeLLo WoRLd')).toBe('Hello World');
        });

        test('should handle input that is already title case', () => {
            expect(toTitleCase('Hello World')).toBe('Hello World');
        });

        test('should handle input with multiple consecutive spaces', () => {
            expect(toTitleCase('hello  world')).toBe('Hello  World');
        });

        test('should handle input with tabs and special whitespace', () => {
            expect(toTitleCase('hello\tworld')).toBe('Hello\tworld');
        });

        test('should handle input with numbers', () => {
            expect(toTitleCase('hello 123 world')).toBe('Hello 123 World');
        });

        test('should handle input with special characters', () => {
            expect(toTitleCase('hello-world test')).toBe('Hello-world Test');
        });

        test('should handle input with punctuation', () => {
            expect(toTitleCase('hello, world!')).toBe('Hello, World!');
        });

        test('should handle single character words', () => {
            expect(toTitleCase('a b c')).toBe('A B C');
        });
    });

    // Edge Test Cases
    describe('Edge cases', () => {
        test('should handle empty string', () => {
            expect(toTitleCase('')).toBe('');
        });

        test('should handle string with only spaces', () => {
            expect(toTitleCase('   ')).toBe('   ');
        });

        test('should handle string with leading spaces', () => {
            expect(toTitleCase('  hello world')).toBe('  Hello World');
        });

        test('should handle string with trailing spaces', () => {
            expect(toTitleCase('hello world  ')).toBe('Hello World  ');
        });

        test('should handle string with only one character', () => {
            expect(toTitleCase('a')).toBe('A');
        });

        test('should handle string with numbers only', () => {
            expect(toTitleCase('123 456')).toBe('123 456');
        });

        test('should handle string with special characters only', () => {
            expect(toTitleCase('!@# $%^')).toBe('!@# $%^');
        });

        test('should handle string with unicode characters', () => {
            expect(toTitleCase('café résumé')).toBe('Café Résumé');
        });

        test('should handle string with emojis', () => {
            expect(toTitleCase('hello 😀 world')).toBe('Hello 😀 World');
        });

        test('should handle very long single word', () => {
            const longWord = 'a'.repeat(1000);
            expect(toTitleCase(longWord)).toBe('A' + 'a'.repeat(999));
        });

        test('should handle string with only uppercase letters', () => {
            expect(toTitleCase('HELLO WORLD')).toBe('Hello World');
        });

        test('should handle string with only lowercase letters', () => {
            expect(toTitleCase('hello world')).toBe('Hello World');
        });

        test('should handle string with newline characters', () => {
            expect(toTitleCase('hello\nworld')).toBe('Hello\nworld');
        });

        test('should handle string with carriage returns', () => {
            expect(toTitleCase('hello\rworld')).toBe('Hello\rworld');
        });

        test('should handle string with non-breaking spaces', () => {
            expect(toTitleCase('hello\u00A0world')).toBe('Hello\u00A0world');
        });

        test('should handle string starting with a number', () => {
            expect(toTitleCase('123abc def')).toBe('123abc Def');
        });

        test('should handle string with apostrophes', () => {
            expect(toTitleCase("don't worry")).toBe("Don't Worry");
        });
    });

    // Large Scale Test Cases
    describe('Performance tests', () => {
        test('should handle large input with many words efficiently', () => {
            const largeInput = 'hello '.repeat(500).trim();
            const result = toTitleCase(largeInput);
            const expectedWords = 'Hello '.repeat(500).trim();
            expect(result).toBe(expectedWords);
        });

        test('should handle input with very long words', () => {
            const longWord = 'a'.repeat(500);
            const input = `${longWord} ${longWord}`;
            const result = toTitleCase(input);
            const expected = `A${'a'.repeat(499)} A${'a'.repeat(499)}`;
            expect(result).toBe(expected);
        });

        test('should handle input with mixed long and short words', () => {
            let input = '';
            for (let i = 0; i < 200; i++) {
                input += 'a'.repeat(i % 10 + 1) + ' ';
            }
            input = input.trim();
            const result = toTitleCase(input);
            expect(result).toBeTruthy();
            const words = result.split(' ');
            expect(words.length).toBeGreaterThan(0);
            // Verify first character of each word is uppercase
            words.forEach(word => {
                if (word.length > 0 && /[a-z]/i.test(word.charAt(0))) {
                    expect(word.charAt(0)).toMatch(/[A-Z]/);
                }
            });
        });

        test('should handle input with numerous spaces between words', () => {
            const input = 'hello' + ' '.repeat(100) + 'world' + ' '.repeat(100) + 'test';
            const result = toTitleCase(input);
            expect(result).toContain('Hello');
            expect(result).toContain('World');
            expect(result).toContain('Test');
        });

        test('should process 300+ word document efficiently', () => {
            const words = [];
            for (let i = 0; i < 300; i++) {
                words.push(`word${i}`);
            }
            const input = words.join(' ');
            const startTime = Date.now();
            const result = toTitleCase(input);
            const endTime = Date.now();
            
            expect(result).toBeTruthy();
            expect(endTime - startTime).toBeLessThan(100); // Should complete in less than 100ms
            const resultWords = result.split(' ');
            expect(resultWords.length).toBe(300);
        });

        test('should handle alternating case patterns efficiently', () => {
            let input = '';
            for (let i = 0; i < 250; i++) {
                input += (i % 2 === 0 ? 'hello' : 'WORLD') + ' ';
            }
            input = input.trim();
            const result = toTitleCase(input);
            expect(result).toBeTruthy();
            const words = result.split(' ');
            // Every odd-indexed word should be 'Hello', every even should be 'World'
            for (let i = 0; i < words.length; i++) {
                expect(['Hello', 'World']).toContain(words[i]);
            }
        });

        test('should handle input with repeated patterns', () => {
            const pattern = 'the quick brown fox jumps over the lazy dog ';
            let input = '';
            for (let i = 0; i < 40; i++) {
                input += pattern;
            }
            input = input.trim();
            const result = toTitleCase(input);
            expect(result).toBeTruthy();
            // Check that all words are properly title cased
            const words = result.split(' ');
            words.forEach(word => {
                if (word.length > 0 && /[a-z]/.test(word)) {
                    expect(word[0]).toMatch(/[A-Z]/);
                }
            });
        });
    });
});

To edit these changes git checkout codeflash/optimize-toTitleCase-mkh64r8z and push.

Codeflash Static Badge

The optimized code achieves a **13% speedup** by eliminating multiple intermediate array allocations and reducing function call overhead.

**Key optimizations:**

1. **Single-pass character iteration**: Instead of `split()` → `map()` → `join()` which creates multiple intermediate arrays, the optimized version processes each character once in a loop, building the result string directly.

2. **Eliminates array overhead**: The original approach:
   - Calls `toLowerCase()` on entire string (allocation #1)
   - Creates array via `split(' ')` (allocation #2)
   - Creates new array via `map()` with per-word `charAt()` + `slice()` + `toUpperCase()` operations (allocation #3 + N word allocations)
   - Joins array back to string (allocation #4)
   
   The optimized version only allocates the final result string.

3. **Reduces function calls**: Eliminates array method overhead (`split`, `map`, `join`) and per-word string methods (`charAt`, `slice`). Instead uses simple character-by-character conditionals.

4. **State-based capitalization**: The `capitalizeNext` flag efficiently tracks when to capitalize without needing to identify word boundaries upfront.

**Performance characteristics by test type:**

- **Best gains**: Tests with many short words (e.g., "a b c", "hello world", 500-word documents) benefit most, as they maximize the impact of avoiding per-word string allocations
- **Moderate gains**: Mixed-case normalization and large single words still benefit from reduced overhead
- **Edge cases**: Empty strings, whitespace-only inputs now have early returns and simpler logic

The optimization is particularly effective for typical use cases involving multiple words, which aligns with the common usage patterns shown in the test suite where most tests involve 2-500 words separated by spaces.
@codeflash-ai codeflash-ai bot requested a review from misrasaurabh1 January 16, 2026 17:44
@codeflash-ai codeflash-ai bot added ⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash labels Jan 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

⚡️ codeflash Optimization PR opened by Codeflash AI 🎯 Quality: High Optimization Quality according to Codeflash

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant