{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "The string [join method](https://docs.python.org/3/library/stdtypes.html#str.join)\n", "can concatenate strings significantly faster than using the '+' operator.\n", "I think Raymond Hettinger talked about this in one of his presentations\n", "archived on pyvideo.org." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "width = 1000" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def foo(width):\n", " horizontal_line = '{'\n", " for i in range(width):\n", " horizontal_line += (' ' + '#ffffff')\n", " horizontal_line += '}'" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1000 loops, best of 3: 210 µs per loop\n" ] } ], "source": [ "%timeit foo(width)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def foo(width):\n", " horizontal_line = (\n", " '{' +\n", " ' '.join(\n", " '#ffffff' for i in range(width)\n", " ) +\n", " '}'\n", " )" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10000 loops, best of 3: 129 µs per loop\n" ] } ], "source": [ "%timeit foo(width)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def foo(width):\n", " horizontal_line = ''.join([\n", " '{',\n", " ' '.join(\n", " '#ffffff' for i in range(width)\n", " ),\n", " '}',\n", " ])" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10000 loops, best of 3: 129 µs per loop\n" ] } ], "source": [ "%timeit foo(width)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.4.3" } }, "nbformat": 4, "nbformat_minor": 0 }