Skip to content
The Chat Archive
claude-sonnet-4-20250514-thinking-32k· Anthropic LMArena Human Preference 140K

This works, do you think you could make it any faster? let mut nonce = [0u8; 12];…

  1. User

    This works, do you think you could make it any faster? let mut nonce = [0u8; 12]; fill_random_bytes(12, &mut nonce, &mut state.random); let mut cipher = ChaCha20::new( GenericArray::from_slice(&state.key), GenericArray::from_slice(&nonce) ); let mut data: Vec = Vec::with_capacity(packet.len() - 1); packet[1..].clone_into(&mut data); cipher.apply_keystream(&mut data); let mut result = Vec::with_capacity(nonce.len() + data.len()); result.extend_from_slice(&nonce); result.extend_from_slice(&data); return Some(result);

  2. Assistant

    Looking at your code, there are several optimization opportunities. Here's a faster version that eliminates unnecessary allocations:

    let mut nonce = [0u8; 12];
    fill_random_bytes(12, &mut nonce, &mut state.random);
    
    let data_len = packet.len() - 1;
    let mut result = vec![0u8; 12 + data_len];
    
    // Copy nonce and data directly into final buffer
    result[..12].copy_from_slice(&nonce);
    result[12..].copy_from_slice(&packet[1..]);
    
    // Apply cipher in-place on the data portion
    let mut cipher = ChaCha20::new(
        GenericArray::from_slice(&state.key),
        GenericArray::from_slice(&nonce)
    );
    cipher.apply_keystream(&mut result[12..]);
    
    return Some(result);
    

    Key optimizations:

    1. Eliminates intermediate data vector - you were creating an extra allocation just to copy data that gets copied again
    2. Single allocation - pre-allocates the final result buffer with exact size using vec![0u8; size]
    3. Direct copying - uses copy_from_slice which is often faster than clone_into + extend_from_slice
    4. In-place encryption - applies the cipher directly on the final buffer

    This reduces allocations from 3 vectors down to 1, and eliminates several copy operations. The performance gain will be most noticeable with larger packets.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.